【问题标题】:Put tags around part of string in Smarty在 Smarty 中将标签放在字符串的一部分周围
【发布时间】:2014-09-30 14:03:34
【问题描述】:

我从MySQL 数据库中获取字符串。示例字符串:

'
{something}Lorem ipsum{/something} dolor sit amet, consectetur adipiscing elit. 
Scrupulum, inquam, abeunti; 
{blablabla}Illa tamen simplicia{blablabla}, vestra versuta.
Non semper, inquam; Sed mehercule pergrata mihi oratio tua. 
Stoici scilicet. Scrupulum, inquam, abeunti;
'

在 php 中,我将字符串分配给 Smarty 变量,如下所示:

$smarty->assign('homePageText', $string);

现在,我希望能够在模板中做这样的事情:

{$homePageText}
  {something}
    <a href="http://www.domain.com/" class="foo">{$}</a>
  {/something}
  {blablabla}
    <b class="bar"><i>{$}</i></b>
  {/blablabla}
{/$homePageText}

所以字符串会变成这样:

'
<a href="http://www.domain.com/" class="foo">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit. 
Scrupulum, inquam, abeunti; 
<b class="bar"><i>Illa tamen simplicia</i></b>, vestra versuta.
Non semper, inquam; Sed mehercule pergrata mihi oratio tua. 
Stoici scilicet. Scrupulum, inquam, abeunti;
'

这样您就可以在 Smarty 模板中的变量部分周围放置标签。 Smarty 3.0中是否已经有这样的功能?或者我怎样才能在 php 5.4 中将它构建到 smarty 中?我希望模板中的 php 代码尽可能少。此外,{something}&lt;tag&gt;{$}&lt;/tag&gt;{/something} 部分不应在 php 文件中,因为每页会有多个模板

【问题讨论】:

标签: php smarty smarty3


【解决方案1】:

我在类似的设置中使用了一个简单的replace 修饰符。但我认为这种方法既不优雅也不灵活。无论如何,我的数据库中的字符串应该是这样的:

'%something1%Lorem ipsum%something2% dolor sit amet, consectetur adipiscing elit. 
Scrupulum, inquam, abeunti; 
%blablabla1%Illa tamen simplicia%blablabla2%, vestra versuta.
Non semper, inquam; Sed mehercule pergrata mihi oratio tua. 
Stoici scilicet. Scrupulum, inquam, abeunti;'

模板中的代码看起来是这样的(删除换行符!):

{$homePageText|replace:'%something1%':'<a href="http://www.domain.com/" class="foo">'
    |replace:'%something2%':'</a>'
    |replace:'%blablabla1%':'<b class="bar"><i>'
    |replace:'%blablabla2%':'</i></b>'
}

我在一个场景中使用它,其中翻译来自数据库表,但模板中的一些 HTML 标记或 URL 是硬编码的。

顺便说一句:你可以使用regex_replace一步插入开始和结束标签,但它并没有真正提高可读性......

|regex_replace:'/%something1%(.*)%something2%/':'<a href="http://www.domain.com/" class="foo">\\1</a>'

【讨论】:

  • 不幸的是你必须去掉换行符,我添加了更好的可读性。对不起;没有测试过。
【解决方案2】:

我在 Smarty 中添加了一个插件:

class SmartyPlugins {

    public static function addTags($string, $search, $openingTag, $closingTag) {
        return str_replace(
            '{/' . $search . '}', 
            $closingTag, 
            str_replace(
                '{' . $search . '}', 
                $openingTag, 
                $string
            )
        );
    }
}

//register the plugin
$smarty->registerPlugin('modifier', 'addTags', array('SmartyPlugins', 'addTags'));

现在我可以在模板中执行此操作:

{$var|addTags:'a':'<a href="http://domain.com">':'</a>'} //changes "Test {a}blablabla{/a} something" to "Test <a href="http://domain.com">blablabla</a> something"

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多