Using smarty in plugins
(Poor mans split from here)
@R_J said:
@hgtonight said:
The development version even has support for adding it via tpl files.Interesting! I recently tried to use Smarty in a plugin but failed because I saw now way of adding variables to Smarty. That's why I was just before making a pull request on GitHub for class.smarty.php:
class Gdn_Smarty { ... public function assign($key, $value = '') { $smarty = $this->smarty(); $smarty->assign($key, $value); }How could I use Smarty without that method?
@peregrine said:
not sure what you are after.just add name to the call in the tpl
$Name = GetValue('name', $Params);
To my understanding Smarty is all about being able to replace such a view:
<h1><?php echo $this->data('Title'); ?></h1> <p><?php echo $this->data('SomethingMeaningful'); ?></p>
with such a template
<h1>{$Title}</h1> <p>{$SomethingMeaningful}</p>
So I've put the above in plugins/smartytest/views/smartytest.tpl
and used a plugin with following method:
public function vanillaController_smartytest_create($sender, $args) { $sender->masterView(); // Add modules. foreach (c('Modules.Vanilla.Panel') as $module) { if ($module != 'MeModule') { $sender->addModule($module); } } $smarty = new Gdn_Smarty(); // This only works with a tweaked smarty class... $smarty->assign('Title', 'JUHU'); $smarty->assign('SomethingMeaningful', 'You bet!'); $sender->render($this->getView('smartytest.tpl')); }
That works exactly as I wanted it to (and as I would expect it). Downside is, there is no such assign()
function in class.smarty.php and that's why I had to add it.
If I had more time for it, I already would have filed a PR. But now I thought maybe hgtonight knows a way to assign variables to the smarty object. That's why I was curious. Otherwise I'm eager to file this PR. You know: I'm like a collector and like to see my avatar above all those files on GitHub and I guess that's the best opportunity to appear in the smarty class!
Comments
You want to expose variables to Smarty templates?
You should be able to hook into the
Gdn_Smarty_Init_Handler($sender)
and assign directly to the$sender
smarty object.Search first
Check out the Documentation! We are always looking for new content and pull requests.
Click on insightful, awesome, and funny reactions to thank community volunteers for their valuable posts.
I'm such an idiot (sometimes)! And now I'm happy I didn't made a PR
$smarty->smarty()->assign(...)
$sender->setData($key, $value)
is assigned to Smarty during the classes init function. So I must only be sure I set it before smarty is initialized. So I could rely on the Garden convention of setData and I'm not bound to Smarty specific syntaxesThat way you can switch between php views and Smarty templates by only changing the filename to render. That's really comfortable!