views:

611

answers:

3

I'm using Smarty and utilizing the config_load respective {#VAR#} variables to implement localization. This is working perfectly fine as long as the content is within the templates, but fails as soon as I have to add dynamic content within the TPL file, i.e. with:

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

Please note each entry within $var contains usually one {#VAR#} entry - and they are not translated (the user will see {#VAR#}).

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

Many, many thanks!


Solution

I ended up by only replacing {$line}<br> in the code above with:

{eval var=$line}

That did the trick for me.

+1  A: 

You are probably looking for something like {eval}

Take a look at {eval} documentation.

On your situation, you could try this:

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 that helps! :)

Carlos Lima
A: 

As you probably noticed smarty parses your template into php code and stores it in templates_c directory. It makes this library run very fast. What you are going to accomplish would require to parse a completly new template every time a looped code is being executed. This would render your application very slow.

I would suggest not storing messages in constatnts, but to store it in templates, eg.

{assign var='lang' value='en'}
{if isset($var) }
    {foreach from=$var item=line}
        {include file="$lang/$line.tpl"}<br>
    {/foreach}
{/if}
hegemon
Tkx hegemon! You make a good point regarding the performace.I'm using this dynamic output to show appropriate error messages to the user. The solution you described above requires one template file for each $var content - isn't there a more elegant solution?
MrG
A: 

a great aproach I've seen was use modifiers for translations. this allow you to translate dynamic content.

all the code its just an example, wont work, just to give you an idea

lets say

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);

}
Gabriel Sosa