Reputation: 21
I want to replace search query with html tag in Smarty template but I have a problem.
When I use html tags in Smarty replace()
function I get an error
This is my code for replace search query with html tag
{$tools[x].tool_title|replace:$q:'<b>$q</b>'}
Upvotes: 2
Views: 2813
Reputation: 111899
You need to use double quotes (to use variable value - otherwise it will be treated as raw string) and you need to use nofilter
For the following code:
{assign var="q" value="sample"}
{assign var="text" value="This is sample text"}
{$text|replace:$q:"<b>$q</b>" nofilter}
Output in page source is:
This is <b>sample</b> text
However you need to know it could be potentially danger. Consider the following code:
{assign var="q" value="sample"}
{assign var="text" value="This is sample text <script>alert('hello');</script>"}
{$text|replace:$q:"<b>$q</b>" nofilter}
it will display JavaScript alert because page source is now:
This is <b>sample</b> text <script>alert('hello');</script>
However it seems you can do something with it using the following code:
{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}
Page source for that will be:
This <b>is</b> <b>sample</b> text <script>alert('hello');</script>
Because you first use escape
modifier to escape everything in $text
variable and then on safe input you perform replace.
Upvotes: 3