Smarty Forum Index Smarty
The discussions here are for Smarty, a template engine for the PHP programming language.

How to use SMARTY variables in JavaScript
Goto page Previous  1, 2
Post new topic   Reply to topic    Smarty Forum Index -> Tips and Tricks
View previous topic :: View next topic  
Author Message

Joined: 16 Apr 2003
Posts: 7359
Location: Lincoln Nebraska, USA

PostPosted: Thu Aug 08, 2013 2:14 pm    Post subject: Re: Use {/literal} tag before the javascript variable Reply with quote

vignates wrote:
Refer this article, which clearly gives how to use smarty variable inside javascript function or code.

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:

{literal}<script type="text/javascript">
var newVar = "{/literal}{$dynamicValue}{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:

<script type="text/javascript">
var newVar = "{$dynamicValue}";

That said, it is possible that there are rogue characters in the smarty var that javascript may not like, so just escape them:

<script type="text/javascript">
var newVar = "{$dynamicValue|escape:javascript}";

The only time {literal} tags are used is when the javascript contains {} characters that you want Smarty to ignore:

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:

var foo = function() {literal}{{/literal}
   return '{$myVar}';

or a clearer method, escape the braces:

var foo = function() {$smarty.lbrace}
   return '{$myVar}';

And of course, don't forget to escape the variable:

var foo = function() {$smarty.ldelim}
   return '{$myVar|escape:javascript}';

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
View user's profile Send private message Visit poster's website
Display posts from previous:   
Post new topic   Reply to topic    Smarty Forum Index -> Tips and Tricks All times are GMT
Goto page Previous  1, 2
Page 2 of 2

Jump to:  
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
Protected by Anti-Spam ACP