|
Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon. |
|
View previous topic :: View next topic |
Author |
Message |
mohrt Administrator
Joined: 16 Apr 2003 Posts: 7368 Location: Lincoln Nebraska, USA
|
Posted: Thu Aug 08, 2013 2:14 pm Post subject: Re: Use {/literal} tag before the javascript variable |
|
|
Food for thought: Smarty doesn't care about "javascript", it doesn't even know what javascript is. What it does care about however, are {} characters in templates that are not part of Smarty syntax. These can create syntax errors.
So, in that example code:
Code: | {literal}<script type="text/javascript">
var newVar = "{/literal}{$dynamicValue}{literal}";
</script>{/literal} |
There is no reason to use {literal}{/literal} tags here, since there are no conflicting {} characters in the javascript. So, this will work just the same:
Code: | <script type="text/javascript">
var newVar = "{$dynamicValue}";
</script>
|
That said, it is possible that there are rogue characters in the smarty var that javascript may not like, so just escape them:
Code: | <script type="text/javascript">
var newVar = "{$dynamicValue|escape:javascript}";
</script>
|
The only time {literal} tags are used is when the javascript contains {} characters that you want Smarty to ignore:
Code: | var foo = function() {
return '{$myVar}';
} |
The above code is fine in Smarty 3, as it will ignore {} surrounded by white space. Smarty 2 however, needs a little help. Either use literal tags like so:
Code: | var foo = function() {literal}{{/literal}
return '{$myVar}';
{literal}}{/literal} |
or a clearer method, escape the braces:
Code: | var foo = function() {$smarty.lbrace}
return '{$myVar}';
{$smarty.rbrace} |
And of course, don't forget to escape the variable:
Code: | var foo = function() {$smarty.ldelim}
return '{$myVar|escape:javascript}';
{$smarty.rdelim} |
Everything above is assuming your Smarty delimiters are { and } respectively. If you change them to something else like {{ }} or <% %> then javascript escapement becomes a non-issue as well. |
|
Back to top |
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|