khernik
khernik

Reputation: 2091

Using class in smarty templates

I am migrating from clean php views to smarty, and I have a problem converting the following template into smarty:

<?php
   use \framework\core;
?>

<h1><?= Core::translate('some string to translate'); ?></h1>

So I want to use some class that's loaded via autoloader, and then use its translate method. How can I do that in smarty?

Upvotes: 0

Views: 1130

Answers (2)

dmitry
dmitry

Reputation: 5039

This is how I did this same task in one of my older projects using Smarty API extension:

// register additional smarty modifiers for I18N 
$this->smarty->register_block("translate", array($this, "smarty_i18n_translate"));
// better alias
$this->smarty->register_block("_", array($this, "smarty_i18n_translate"));


// translation function
public function smarty_i18n_translate($params, $content, &$smarty, &$repeat)
{
    if (isset($content))
    {
        if (isset($params['resourceID']))
        {
            $resourceID = $params['resourceID'];
            unset($params['resourceID']);
        }
        else
            $resourceID = NULL;

        // setting context vars if specified
        foreach ($params as $key => $val)
        {
            $this->setContextVar($key, $val);
        }

        // Core::translate($content); ?
        return $this->translate($content, $resourceID);
    }

    return '';
}

This allows writing in views (I used {? as smarty tag delimiter):

<span class="label">{?_?}Operation type{?/_?}:</span>

One note: this was for some pretty ancient version of Smarty, they may have changed details of API, but it seems register methods are still there.

Btw in the docs there is this same problem illustrated as example: http://www.smarty.net/docsv2/en/api.register.block.tpl

Upvotes: 1

Ceeee
Ceeee

Reputation: 1442

try this logic/way, hope you might get some idea..

<?php
   $my_obj = new MyClass();

   $smarty->left_delimeter('{{');
   $smarty->right_delimeter('}}');

   $smarty->assign('my_obj', $my_obj);
   $smarty->display('your.html');
?>

Then on your html

<h1>{{ $my_obj->translate('some string to translate'); }}</h1>

Upvotes: 0

Related Questions