简体   繁体   English

PHP和Smarty的动态内容

[英]Dynamic content with PHP & Smarty

I'm using Smarty and utilizing the config_load respective {#VAR#} variables to implement localization. 我正在使用Smarty,并利用config_load各自的{#VAR#}变量来实现本地化。 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, ie with: 只要内容在模板中,此方法就可以很好地工作,但是一旦我必须在TPL文件中添加动态内容时,即会失败,即:

{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#} ). 请注意,$ var中的每个条目通常包含一个{#VAR#}条目-它们不会被翻译 (用户将看到{#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: 最后,我仅将上面代码中的{$line}<br>替换{$line}<br>

{eval var=$line}

That did the trick for me. 那对我有用。

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

}

You are probably looking for something like {eval} 您可能正在寻找类似{eval}的东西

Take a look at {eval} documentation. 看一下{eval}文档。

On your situation, you could try this: 根据您的情况,您可以尝试以下操作:

example.php 使用example.php

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

example.config example.config

OK = Okay
CANCEL = Nevermind

example.tpl 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! 希望有帮助! :) :)

As you probably noticed smarty parses your template into php code and stores it in templates_c directory. 您可能已经注意到smarty将模板解析为php代码,并将其存储在templates_c目录中。 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. 我建议不要将消息存储在constatnts中,而是将其存储在模板中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM