Dynamic content with PHP and Smarty

I am using Smarty and using {#VAR#}

config_load variables to implement localization. This works fine as long as the content is inside templates, but fails as soon as I have to add dynamic content to the TPL file, that is, with:

{if isset($var) }
    {foreach from=$var item=line}
        {$line}<br>
    {/foreach}
{/if}

      

Note that each entry in $ var usually contains one entry {#VAR#}

- and they are not translated (the user will see {#VAR#}

).

What is the correct way to implement localization in this case?


Decision

I ended up replacing it {$line}<br>

with the code above:

{eval var=$line}

      

It helped me.

+1


a source to share


3 answers


You are probably looking for something like {eval}

Take a look at the {eval} documentation.

In your situation, you can try the following:

example.php

<?php
  (...)
  $var = array("{#OK#}", "{#CANCEL#}");
  $smarty->assign('var', $var);
  $smarty->display('example.tpl');
?>

      



example.config

OK = Okay
CANCEL = Nevermind

      

example.tpl

{config_load file='example.config'}

<h1>Template stuff</h1>

{if isset($var) }
  {foreach from=$var item=line}
    {eval var=$line}<br>
  {/foreach}
{/if}

      

Hope it helps! :)

+1


a source


a great approach I've seen was using modifiers for translations. it allows you to translate dynamic content.

all the code its just an example, doesn't work just to give you an idea

allows

your tpl



{"Hello word! How are you %s?"|translate:"Gabriel"}


{$myvar|translate:"Gabriel"}

      

your modifier

function smarty_modifier_translate($content, $args) {
  $lang = Env::getLanguage();
  return vsprintf($lang->getTranslation($content), $args);

}

      

+2


a source


As you probably noticed, smarty parses your template in php code and stores it in templates_c directory. This makes this library very fast. What you are about to accomplish will require parsing a completely new template every time the code loop is executed. This will make your application very slow.

I would suggest not storing messages in constants, but storing them in templates, for example.

{assign var='lang' value='en'}
{if isset($var) }
    {foreach from=$var item=line}
        {include file="$lang/$line.tpl"}<br>
    {/foreach}
{/if}

      

0


a source







All Articles