i have problem with rendering template in ZF2, where template is in string in variable. There is simple example:
$template = "<div>easy</div>";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);
$renderer = new \Zend\View\Renderer\PhpRenderer();
$html = $renderer->render($view);
This code fail on rendering, the renderer think that the template is a path to file. And iam reallz not sure how to tell rendere its a string.
Thx for your time and respond.
You have to extend the PhpRenderer class and override the render method, in such a way that will use the string in the $template as the actual template:
class MyPhpRenderer extends PhpRenderer {
public function render($nameOrModel, $values = null)
{
if ($nameOrModel instanceof Model) {
$model = $nameOrModel;
$nameOrModel = $model->getTemplate();
if (empty($nameOrModel)) {
throw new Exception\DomainException(sprintf(
'%s: received View Model argument, but template is empty',
__METHOD__
));
}
$options = $model->getOptions();
foreach ($options as $setting => $value) {
$method = 'set' . $setting;
if (method_exists($this, $method)) {
$this->$method($value);
}
unset($method, $setting, $value);
}
unset($options);
// Give view model awareness via ViewModel helper
$helper = $this->plugin('view_model');
$helper->setCurrent($model);
$values = $model->getVariables();
unset($model);
}
// find the script file name using the parent private method
$this->addTemplate($nameOrModel);
unset($nameOrModel); // remove $name from local scope
$this->__varsCache[] = $this->vars();
if (null !== $values) {
$this->setVars($values);
}
unset($values);
// extract all assigned vars (pre-escaped), but not 'this'.
// assigns to a double-underscored variable, to prevent naming collisions
$__vars = $this->vars()->getArrayCopy();
if (array_key_exists('this', $__vars)) {
unset($__vars['this']);
}
extract($__vars);
unset($__vars); // remove $__vars from local scope
while ($this->__template = array_pop($this->__templates)) {
$this->__file = $this->resolver($this->__template);
try {
if (!$this->__file) {
$this->__content = $this->__template; // this line does what you need
}else{
ob_start();
$includeReturn = include $this->__file;
$this->__content = ob_get_clean();
}
} catch (\Exception $ex) {
ob_end_clean();
throw $ex;
}
if ($includeReturn === false && empty($this->__content)) {
throw new Exception\UnexpectedValueException(sprintf(
'%s: Unable to render template "%s"; file include failed',
__METHOD__,
$this->__file
));
}
}
$this->setVars(array_pop($this->__varsCache));
if ($this->__filterChain instanceof FilterChain) {
return $this->__filterChain->filter($this->__content); // filter output
}
return $this->__content;
}
}
and then you code should look like:
$template = "<div>easy</div>";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);
$renderer = new MyPhpRenderer();
$html = $renderer->render($view);
Try by replacing '\' with _ underscore as Zend_View_Renderer_PhpRenderer
Related
in my PagesController::display() i have this code :
class PagesController extends AppController {
public function display(...$path) {
$count = count($path);
if (!$count) {
return $this->redirect('/');
}
if (in_array('..', $path, true) || in_array('.', $path, true)) {
throw new ForbiddenException();
}
$page = $subpage = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
$this->set(compact('page', 'subpage'));
try {
$this->render(implode('/', $path));
} catch (MissingTemplateException $exception) {
if (Configure::read('debug')) {
throw $exception;
}
throw new NotFoundException();
}
$test = "abc";
$this->set(compact('test'));
}
}
That's almost the same as the standard pages controller, I added the last two lines.
My home.ctp template contains:
<?php
var_dump($test);
...
When I access the site, this outputs:
C:\wamp64\www\site\src\Template\Pages\home.ctp:322:null
Which is confusing because debug kit shows that this variable was set:
Why is the test variable not available in the home.ctp template?
Render is being called before set
try {
$this->render(implode('/', $path)); <----
} catch (MissingTemplateException $exception) {
if (Configure::read('debug')) {
throw $exception;
}
throw new NotFoundException();
}
$test = "abc";
$this->set(compact('test')); <-----
}
The call to set is simply too late - it is after the template has already been used.
To have any effect the set call must be before calling render i.e.:
$test = 'abc';
$this->set(compact('page', 'subpage', 'test')); <---
try {
$this->render(implode('/', $path)); <---
...
Why does the variable show up in DebugKit?
DebugKit interrogates the controller instance to obtain the view variables used - But this runs right at the end of the request. This is the reason it is found by debug kit even though it was not available in the template.
I am making an app that translates a word from one language to English and gets information about it (e.g. definition, use in a sentence, synonyms, sound representation)
What my function does:
Searches for the translation in the database. If it is found, we return it.
If it is not found we translate a word using google translate, or Yandex translate API.
If translation is found we download it's sound representation, save the translation to the database and add additional information from other API's
We return a json response with all of the information.
Now my controllers method is really big and I can't find a cleaner way to go about it.
Any help is appreciated.
public function store(Request $request)
{
$translated = $request->get('translated');
$translation = $this->translation->findBy('translated', $translated)->first();
if ($translation) {
return Response::json(['translation' => $this->translation->with(['examples', 'definitions', 'synonyms', 'images'])->find($translation->id)], ResponseCode::HTTP_CREATED);
}
$data = $request->all();
$data['translation'] = $this->translate($translated);
if ($translated == $data['translation']) {
Log::info('Translation not found: ' . $data['translation']);
return $this->translationNotFound();
}
$downloader = new Downloader(new GoogleSpeechDownloader());
$filename = $downloader->download($data['translation']);
if ($filename) $data['sound_name'] = $filename;
$translation = $this->translation->create($data);
$this->createDefinition($translation);
$this->createExample($translation);
$this->createSynonym($translation);
return Response::json(['translation' => $this->translation->with(['examples', 'definitions', 'synonyms', 'images'])->find($translation->id)], ResponseCode::HTTP_CREATED);
}
private function translationNotFound()
{
return Response::json(['error' => 'Vertimas nerastas.'], ResponseCode::HTTP_NOT_FOUND);
}
private function createDefinition($translation)
{
$definition = new Definition();
$definer = new Definer(new DictionaryApiDefiner());
try {
$definition->definition = $definer->getDefinition($translation->translation);
$definition->approved = true;
$translation->definitions()->save($definition);
} catch (\Exception $e) {
Log::alert('Definition for word ' . $translation->translation . ' not found.');
}
}
private function createExample($translation)
{
$example = new Example();
$exampler = new ExampleCreator(new YourDictionaryGouteParserExampler());
try {
$example->example = $exampler->getExample($translation->translation);
$example->approved = true;
$translation->examples()->save($example);
} catch (\Exception $e) {
Log::alert('Example for word ' . $translation->translation . ' not found.');
}
}
private function createSynonym($translation)
{
$creator = new SynonymCreator(new BigHugeLabsSynonymCreator());
foreach ($creator->getSynonyms($translation->translation) as $s) {
$synonym = new Synonym();
$synonym->synonym = $s;
$synonym->approved = true;
$translation->synonyms()->save($synonym);
}
}
private function translate($translated)
{
$translator = new Translator(new GoogleTranslator());
try {
return $translator->translate($translated);
} catch (\Exception $e) {
Log::critical($e->getMessage());
}
$translator = new Translator(new YandexTranslator());
return $translator->translate($translated);
}
If you want cleaner code, just make a class for this job. Two classes for this two API's and in the controller make the check for the word, if not exist in the database, check in the other two API's, just split every action to method in the new two classes that you will make.
I am generating a pdf from the mPDF library using the Yii framework. For this PDF I need to add charts generated on the server, so I'm using the pChart library to generate them. I created a simple object class to set the pChart properties in an easier way for the PDF.
This is the class object:
<?php
Class Chart {
protected $fontsFolder = null;
protected $data = array();
protected $resolution = array();
public $chartType = null;
public $fontSize = 18;
public $displayValues = false;
public $dirFile = null;
function __construct() {
Yii::import('application.vendors.pChart.class.*', true);
$this->fontsFolder = Yii::getPathOfALias('application.vendors.pChart.fonts');
}
// Set data points
public function data($data) {
if(!isset($data))
throw new CException('Data array missing');
if(!is_array($data))
throw new CException('Data must be an array');
$this->data[] = $data;
}
// Set label points
public function labels($labels) {
if(!isset($labels))
throw new CException('Labels data must be assgined');
if(!is_array($labels))
throw new CException('Labels data must be an array');
if(isset($this->data['labels']))
throw new CException('Labels data is already assigned');
$this->data['labels'] = $labels;
}
// Set resolution image
public function resolution($x, $y) {
if(isset($x) && isset($y)) {
if(is_array($x) && is_array($y))
throw new CException('Array to String error');
$this->resolution['x'] = $x;
$this->resolution['y'] = $y;
} else
throw new CException('Resolution data missing');
}
public function Debug() {
var_dump($this->fontsFolder, $this->data, $this->resolution);
}
// Render chart with given data
public function renderChart() {
if(!$this->data)
throw new CException('Data property must be assigned');
if(!$this->resolution)
throw new CException('Resolution property must be assigned');
if(!$this->chartType)
throw new CException('Chart type cannot be null');
if(!$this->dirFile)
throw new CException('Directory file must be assigned');
$this->render();
}
protected function render() {
switch ($this->chartType) {
case 'lineChart':
$this->lineChart();
break;
default:
throw new CEXception('"'.$this->chartType.'" is not a valid chart type');
break;
}
}
protected function lineChart() {
include('pDraw.class.php');
include('pImage.class.php');
include('pData.class.php');
$data = new pData();
foreach($this->data as $key => $value) {
if(is_int($key))
$data->addPoints($value);
}
$data->addPoints($this->data['labels'], 'labels');
$data->setAbscissa('labels');
$picture = new pImage($this->resolution['x'], $this->resolution['y'], $data);
$picture->setFontProperties(array('FontName'=>$this->fontsFolder.'/Forgotte.ttf'), $this->fontSize);
$picture->setGraphArea(60, 40, 970, 190);
$picture->drawScale(array(
'GridR'=>200,
'GridG'=>200,
'GridB'=>200,
'DrawXLines'=>false
));
$picture->drawLineChart(array('DisplayValues'=>$this->displayValues));
$picture->render($this->dirFile);
}
}
?>
And here is how I'm instantiating the object with PDF settings:
<?php
Class SeguimientoController extends Controller {
// public $layout = '//layouts/column2';
public function actionIndex() {
// Cargar libreria pdf y estilos
$mPDF = Yii::app()->ePdf->mpdf();
$mPDF->debug = true;
$mPDF->showImageErrors = true;
$stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css.reporte') . '/main.css');
$mPDF->WriteHTML($stylesheet, 1);
// Generate first chart
$chart = new Chart;
$chart->data(array(1,2,3,4,5));
$chart->Labels(array('asd', 'dead', 'eads', 'daed', 'fasd'));
$chart->resolution(1000, 200);
$chart->chartType = 'lineChart';
$chart->displayValues = true;
$chart->dirFile = Yii::getPathOfAlias('webroot.images').'/chart.png';
$chart->renderChart();
$mPDF->WriteHTml(CHtml::image('/basedato1/images/chart.png', 'chart'), 2);
// Generate second chart
$chart1 = new Chart;
$chart1->data(array(1,2,3,4,5));
$chart1->Labels(array('asd', 'dead', 'eads', 'daed', 'fasd'));
$chart1->resolution(1000, 200);
$chart1->chartType = 'lineChart';
$chart1->displayValues = true;
$chart1->dirFile = Yii::getPathOfAlias('webroot.images').'/chart.png';
$chart1->renderChart();
$mPDF->WriteHTml(CHtml::image('/basedato1/images/chart.png', 'chart'), 2);
$mPDF->OutPut();
}
}
?>
By testing the output of the view step by step, everything goes fine, the chart is rendered and saved as a temp file so the pdf can gather it. But when I have to render the second chart, I get a fatal error.
I have tried creating another class to be accessed by static functions because I thought the error could be made from multiple instances of the same object. But again, on second render I get the same error.
Just in case, if you need to know how the error outputs, here it is: Fatal error: Cannot redeclare class pDraw in C:\Servidor\basedato1\protected\vendors\pChart\class\pDraw.class.php on line 104.
Use include_once instead of include.
include_once('pDraw.class.php');
include_once('pImage.class.php');
include_once('pData.class.php');
I am using joomla 2.5, I am working on custom component of joomla . I have created the form in backend admin page. what i need is , i want to save the post data of form in params row of that component in database of #_extensions.
Here is my tables/component.php
<?php defined('_JEXEC') or die('Restricted access');
jimport('joomla.database.table');
class componentTablecomponent extends JTable {
function __construct(&$db)
{
parent::__construct('#__extensions', 'extension_id', $db);
}
public function bind($array, $ignore = '')
{
if (isset($array['params']) && is_array($array['params']))
{
// Convert the params field to a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
public function load($pk = null, $reset = true)
{
if (parent::load($pk, $reset))
{
// Convert the params field to a registry.
$params = new JRegistry;
$params->loadJSON($this->params);
$this->params = $params;
return true;
}
else
{
return false;
}
} public function store() {
parent::store(null);
}
}
Instead of saving the $data in params row of that component . This code is creating new empty rows in that table(data is saving in those params field).
Here is my save() function in controllers/component.php
public function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Check if the user is authorized to do this.
if (!JFactory::getUser()->authorise('core.admin'))
{
`JFactory::getApplication()->redirect('index.php',JText::_('JERROR_ALERTNOAUTHOR'));`
return;
}
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('component');
$form = $model->getForm();
$data = JRequest::getVar('jform', array(), 'post', 'array');
print_r($data);
// Validate the posted data.
$return = $model->validate($form, $data);
// Check for validation errors.
if ($return === false)
{
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Redirect back to the edit screen.
$this->setRedirect(JRoute::_('somelink',false));
return false;
}
// Attempt to save the configuration.
$data = $return;
$return = $model->save($data);
// Check the return value.
if ($return === false)
{
// Save failed, go back to the screen and display a notice.
$message = JText::sprintf('JERROR_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php/somelink','error');
return false;
}
// Set the success message.
$message = JText::_('COM_CONFIG_SAVE_SUCCESS');
// Set the redirect based on the task.
switch ($this->getTask())
{
case 'apply':
$this->setRedirect('somelink',$message);
break;
case 'cancel':
case 'save':
default:
$this->setRedirect('index.php', $message);
break;
}
return true;
}
models/component.php
public function save($data) {
parent::save($data);
return true;
}
I thinks these codes are enough . I can add more codes if you need.
If you want to store params in the extension table, why not just use com_config for it?
See http://docs.joomla.org/J2.5:Developing_a_MVC_Component/Adding_configuration
Then you don't have to do anything besides creating the config.xml and adding a link to the config options in the toolbar.
I have come up with a solution . it works for me . By using this method you can control save () functions i.e. you can run your custom php scripts on save, apply toolbar buttons.
I copied save(),save($data), store($updateNulls = false) functions from com_config component , I have copied the layout from component view . Removed the buttons. Added toolbar buttons in .html.php file.
controllers/mycomponent.php
<?php
defined('_JEXEC') or die;
class componentControllermycomponent extends JControllerLegacy {
function __construct($config = array())
{
parent::__construct($config);
// Map the apply task to the save method.
$this->registerTask('apply', 'save');
}
function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Set FTP credentials, if given.
JClientHelper::setCredentialsFromRequest('ftp');
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('mymodel');
$form = $model->getForm();
$data = JRequest::getVar('jform', array(), 'post', 'array');
$id = JRequest::getInt('id');
$option = 'com_mycomponent';
// Check if the user is authorized to do this.
if (!JFactory::getUser()->authorise('core.admin', $option))
{
JFactory::getApplication()->redirect('index.php', JText::_('JERROR_ALERTNOAUTHOR'));
return;
}
// Validate the posted data.
$return = $model->validate($form, $data);
// Check for validation errors.
if ($return === false) {
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Save the data in the session.
$app->setUserState('com_iflychat.config.global.data', $data);
// Redirect back to the edit screen.
$this->setRedirect(JRoute::_('index.php?option=com_mycomponent&view=component&component='.$option.'&tmpl=component', false));
return false;
}
// Attempt to save the configuration.
$data = array(
'params' => $return,
'id' => $id,
'option' => $option
);
// print_r($data);
$return = $model->save($data);
// Check the return value.
if ($return === false)
{
// Save the data in the session.
$app->setUserState('com_config.config.global.data', $data);
// Save failed, go back to the screen and display a notice.
$message = JText::sprintf('JERROR_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php?option=com_mycomponent&view=component&component='.$option.'&tmpl=component', $message, 'error');
return false;
}
// Set the redirect based on the task.
switch ($this->getTask())
{
case 'apply':
$message = JText::_('COM_MYCOMPONENT_SAVE_SUCCESS');
print_r($data);
$this->setRedirect('index.php?option=com_mycomponent&view=myview&layout=edit', $message);
break;
case 'save':
default:
$this->setRedirect('index.php');
break;
}
return true;
}
function cancel()
{
$this->setRedirect('index.php');
}
}
models/mymodel.php
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.modelform');
class componentModelmymodel extends JModelForm {
protected $event_before_save = 'onConfigurationBeforeSave';
protected $event_after_save = 'onConfigurationAfterSave';
public function getForm($data = array(), $loadData = true){
// Get the form.
$form = $this->loadForm('com_mycomponent.form', 'config',
array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)){
return false;
}
return $form;
}
public function save($data)
{
$dispatcher = JDispatcher::getInstance();
$table = JTable::getInstance('extension');
$isNew = true;
// Save the rules.
if (isset($data['params']) && isset($data['params']['rules']))
{
$rules = new JAccessRules($data['params']['rules']);
$asset = JTable::getInstance('asset');
if (!$asset->loadByName($data['option']))
{
$root = JTable::getInstance('asset');
$root->loadByName('root.1');
$asset->name = $data['option'];
$asset->title = $data['option'];
$asset->setLocation($root->id, 'last-child');
}
$asset->rules = (string) $rules;
if (!$asset->check() || !$asset->store())
{
$this->setError($asset->getError());
return false;
}
// We don't need this anymore
unset($data['option']);
unset($data['params']['rules']);
}
// Load the previous Data
if (!$table->load($data['id']))
{
$this->setError($table->getError());
return false;
}
unset($data['id']);
// Bind the data.
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Trigger the oonConfigurationBeforeSave event.
$result = $dispatcher->trigger($this->event_before_save, array($this->option . '.' . $this->name, $table, $isNew));
if (in_array(false, $result, true))
{
$this->setError($table->getError());
return false;
}
// Store the data.
if (!$table->store())
{
$this->setError($table->getError());
return false;
}
// Clean the component cache.
$this->cleanCache('_system');
// Trigger the onConfigurationAfterSave event.
$dispatcher->trigger($this->event_after_save, array($this->option . '.' . $this->name, $table, $isNew));
return true;
}
function getComponent()
{
$result = JComponentHelper::getComponent('com_mycomponent');
return $result;
}
}
tables/mycomponent.php
<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
// import Joomla table library
jimport('joomla.database.table');
/**
* Hello Table class
*/
class componentTableMycomponent extends JTable
{
function __construct(&$db)
{
parent::__construct('#__extensions', 'extension_id', $db);
}
public function bind($array, $ignore = '')
{
if (isset($array['params']) && is_array($array['params']))
{
// Convert the params field to a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
public function load($pk = null, $reset = true)
{
if (parent::load($pk, $reset))
{
// Convert the params field to a registry.
$params = new JRegistry;
$params->loadJSON($this->params);
$this->params = $params;
return true;
}
else
{
return false;
}
}
public function store($updateNulls = false)
{
// Transform the params field
if (is_array($this->params)) {
$registry = new JRegistry();
$registry->loadArray($this->params);
$this->params = (string)$registry;
}
$date = JFactory::getDate();
$user = JFactory::getUser();
if ($this->id) {
// Existing item
$this->modified = $date->toSql();
$this->modified_by = $user->get('id');
} else {
// New newsfeed. A feed created and created_by field can be set by the user,
// so we don't touch either of these if they are set.
if (!intval($this->created)) {
$this->created = $date->toSql();
}
if (empty($this->created_by)) {
$this->created_by = $user->get('id');
}
}
// Verify that the alias is unique
$table = JTable::getInstance('Yourinstance', 'mycomponentTable');
if ($table->load(array('alias'=>$this->alias, 'catid'=>$this->catid)) && ($table->id != $this->id || $this->id==0)) {
$this->setError(JText::_('COM_CONTACT_ERROR_UNIQUE_ALIAS'));
return false;
}
// Attempt to store the data.
return parent::store($updateNulls);
}
}
Note : your config.xml file should be in models/forms folder.
I just stuck at a point.
To render Forms in Smarty Template.
Well, smarty is well configured in my silex project.
here is the Code in my controller class.
$loginForm = $app['form.factory']
->createBuilder(new Form\UserLogin())
->getForm();
$app['smarty']->assign('loginForm', $loginForm->createView());
return $app['smarty']->render('login.tpl');
Here is the code in my tpl file
{block name="headline"}
<h1>User Login</h1>
{/block}
{block name="content"}
<div>
{form_widget(loginForm)}
</div>
{/block}
And i am getting this exception.
SmartyCompilerException:
Syntax Error in template "/home/Symfony/demo/App/View/login.tpl" on line 8
"{form_widget(loginForm)}" unknown function "form_widget"
Edit:
Ok i found the issue but not getting the solution.
Following is SmartyServiceProvider Class.
<?php
namespace App\ServiceProvider;
use Silex\Application;
use \Symfony\Component\HttpFoundation\Request;
use Silex\ServiceProviderInterface;
use App\Classes\Smarty;
use NoiseLabs\Bundle\SmartyBundle\Form\SmartyRendererInterface;
use \NoiseLabs\Bundle\SmartyBundle\Extension\AbstractExtension;
use \NoiseLabs\Bundle\SmartyBundle\Extension\FormExtension;
use \NoiseLabs\Bundle\SmartyBundle\Form;
class SmartyServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['smarty.auto-render'] = true;
$app['smarty.extension'] = $app->protect(
function (AbstractExtension $extension, Smarty $smarty = null) use ($app) {
if ($smarty == null) {
$smarty = $app['smarty'];
}
/** #var $plugin \NoiseLabs\Bundle\SmartyBundle\Extension\Plugin\AbstractPlugin */
/** #var $filter \NoiseLabs\Bundle\SmartyBundle\Extension\Filter\AbstractFilter */
foreach ($extension->getPlugins() as $plugin) {
//print $plugin->getName() . " | " . $plugin->getType() . "<br>";
$smarty->registerPlugin($plugin->getType(), $plugin->getName(), $plugin->getCallback());
}
foreach ($extension->getFilters() as $filter) {
$smarty->registerFilter($filter->getType(), $filter->getCallback());
}
}
);
$app['smarty.extensions'] = $app->protect(
function (array $extensions, Smarty $smarty = null) use ($app) {
foreach ($extensions as $extension) {
$app['smarty.extension']($extension, $smarty);
}
}
);
$app['smarty'] = $app->share(
function () use ($app) {
$app['directory.smarty.plugins'] = $app['directory.root.app'] . '/Classes/Smarty/Plugins';
$smarty = isset($app['smarty.instance']) ? $app['smarty.instance'] : new Smarty(
$app,
isset($app['smarty.primary.template.dir'])
? $app['smarty.primary.template.dir']
: $app['directory.root.view'],
false
);
if (isset($app["smarty.options"]) && is_array($app["smarty.options"])) {
foreach ($app["smarty.options"] as $smartyOptionName => $smartyOptionValue) {
$smarty->$smartyOptionName = $smartyOptionValue;
}
}
$smarty->assign("app", $app);
if (isset($app['smarty.configure'])) {
$app['smarty.configure']($smarty);
}
$extensions = [];
//$extensions[] = new \NoiseLabs\Bundle\SmartyBundle\Extension\FormExtension();
$extensions[] = new \NoiseLabs\Bundle\SmartyBundle\Extension\RoutingExtension($app['url_generator']);
$extensions[] = new \App\Classes\Smarty\HookExtension();
$app['smarty.extensions']($extensions, $smarty);
return $smarty;
}
);
}
public function boot(Application $app)
{
}
}
Here in that class i have loaded extensions of SmartyBundle here.
Here I'll have to load FormExtensions.
$extensions = [];
$extensions[] = new \NoiseLabs\Bundle\SmartyBundle\Extension\FormExtension('Don't know how to get SmartyRendererInterface instance here');
$extensions[] = new \NoiseLabs\Bundle\SmartyBundle\Extension\RoutingExtension($app['url_generator']);
$extensions[] = new \App\Classes\Smarty\HookExtension();
$app['smarty.extensions']($extensions, $smarty);
The correct syntax for the Form Widget is:
{form_widget form=$loginForm}
From your example it's not clear the out from $loginForm->createView() and you're lacking the form tags ( ie )that normally surround the Form widget. If the createView includes these you make be not need the form widget and just need to output the entire form HTML as:
{$loginForm}