MrG
MrG

Reputation: 5287

Dynamic content with PHP & Smarty

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?


Solution

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

{eval var=$line}

That did the trick for me.

Upvotes: 1

Views: 1890

Answers (3)

Gabriel Sosa
Gabriel Sosa

Reputation: 7956

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

}

Upvotes: 2

hegemon
hegemon

Reputation: 6764

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}

Upvotes: 0

Carlos Lima
Carlos Lima

Reputation: 4182

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

Upvotes: 1

Related Questions