在Smarty模板中用html标签替换字符串

时间:2014-08-20 11:53:58

标签: security replace smarty xss

我想在Smarty模板中用html标签替换搜索查询,但我遇到了问题。

当我在Smarty replace()函数中使用html标记时,我收到错误

这是我用html标签替换搜索查询的代码

{$tools[x].tool_title|replace:$q:'<b>$q</b>'}  

1 个答案:

答案 0 :(得分:2)

你需要使用双引号(使用变量值 - 否则它将被视为原始字符串),你需要使用nofilter

以下代码:

{assign var="q" value="sample"}
{assign var="text" value="This is sample text"}
{$text|replace:$q:"<b>$q</b>" nofilter}

页面来源的输出是:

This is <b>sample</b> text

然而,您需要知道它可能存在潜在危险。请考虑以下代码:

{assign var="q" value="sample"}
{assign var="text" value="This is sample text <script>alert('hello');</script>"}
{$text|replace:$q:"<b>$q</b>" nofilter}

它将显示JavaScript警报,因为页面源现在是:

This is <b>sample</b> text <script>alert('hello');</script>

但是,您似乎可以使用以下代码执行某些操作:

{assign var="q" value="sample"}
{assign var="text" value="This <b>is</b> sample text <script>alert('hello');</script>"}
{$text|escape|replace:$q:"<b>$q</b>" nofilter}

页面来源为:

This &lt;b&gt;is&lt;/b&gt; <b>sample</b> text &lt;script&gt;alert(&#039;hello&#039;);&lt;/script&gt;

因为您首先使用escape修饰符来转义$text变量中的所有内容,然后在安全输入中执行替换。

相关问题