Question

I have the following Smarty template which is shown in its' entirety which generates some JavaScript.

As you can see I am opening {literal} and closing {/literal} tags all throughout this code snippet, which looks a bit messy and unruly. Is there a better way to write this that would allow the code to appear tidier and more manageable should it have to change in the future?

{literal}
<script type="text/javascript">
var _roi = _roi || [];

// Base Order Details 
_roi.push(['_setMerchantId', '{/literal}{$merchant_id}{literal}']); 
_roi.push(['_setOrderId', '{/literal}{$order_id}{literal}']);
_roi.push(['_setOrderAmount', '{/literal}{$order_total}{literal}']);
_roi.push(['_setOrderNotes', '{/literal}{$order_notes}{literal}']);

// Line Items
{/literal}
{foreach from=$line_items item=line name=items}
    {literal}
    _roi.push(['_addItem', 
    '{/literal}{$line.sku}{literal}',
    '{/literal}{$line.title}{literal}',
    '{/literal}{$line.category_id}{literal}',
    '{/literal}{$line.category}{literal}',
    '{/literal}{$line.price}{literal}',
    '{/literal}{$line.quantity}{literal}'
    ]);
    {/literal}
{/foreach}
{literal}

// Submit Transaction to SDC ROI tracker
_roi.push(['_trackTrans']);
</script>
<script type="text/javascript" src="{/literal}{$url}{literal}"></script>{/literal}
Was it helpful?

Solution

You only need {literal} tags if you're using curly brackets { and } in your javascript code. From what I see, you don't use any of these, so I guess your code would play without any {literal} tags just as well. Even if you were to use a couple of curly brackets, you could use {ldelim} and {rdelim} in their place, if that would save you some tags (and gain readability)

(The above apply for smarty 2)

OTHER TIPS

You can make use of the $auto_literal setting (enabled by default) and make sure that any curly brackets in your JavaScript code are surrounded by whitespace (which they usually should be). Then {literal} wont't be necessary anymore.

In Smarty templates, the { and } braces will be ignored so long as they are surrounded by white space.

Use {ldelim} for { and {rdelim} for }

UPDATE: Per the comments below this

{literal}{{/literal} and {literal}}{/literal}

would be replaced by

{ldelim} {rdelim}

However periklis has the correct answer to the code in the original post. But to answer the question of alternatives to {literal} in javascript. Example building json in Smarty.

{capture assign="row"}{foreach from=$list item=item}
  {ldelim}key1:'{$item['key1val']}',key2:'{$item['key2val']}'{rdelim},
{/foreach}{/capture}
var jsonList = [ {row|trim:','} ];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top