Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative to Smarty {literal} tags for dynamic JavaScript

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}
like image 618
crmpicco Avatar asked Dec 20 '22 09:12

crmpicco


2 Answers

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)

like image 186
periklis Avatar answered Feb 13 '23 04:02

periklis


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.

like image 25
Fabian Schmengler Avatar answered Feb 13 '23 02:02

Fabian Schmengler