Using Smarty variables inside Javascript

I looked for appropriate answers for this on the smarty site, and the resounding answer was escaping javascript’s {}s with {literal}’s

Smarty template vars and Javascript functions
How to use Javascript codes in template files?
Access Smarty value with javascript

They basically all say to do something like this:

// $question_ids_json = ["1","2","3","4","5"]
{literal}
<script>
$(document).ready(function(){
	var question_ids = {/literal}{$question_ids_json}{literal};
	
	alert(question_ids[0]);

});
</script>
{/literal}

So they want to put everything in a literal tag, and then basically escape that literal tag when smarty needs to be used.

I didn’t like this, so I put the value in a hidden input and then just retrieved that input in the javascript, thereby keeping the js clean of smarty shenanigans:

<input type="hidden" id="question_ids" value='{$question_ids_json}'/>

<script>
$(document).ready(function(){
	//var question_ids = {$question_ids_json};
	var question_ids = eval($('#question_ids').val());
	
	alert(question_ids[0]);


});
</script>

But this is just a matter of personal preference.

4 Comments

  1. Omar says:

    Hello,

    Thanks For this article, however no one of those parts of code work.
    For example for the second code i get the error:

    TypeError: question_ids is undefined
    [Stopper sur une erreur]

    alert(question_ids[0]);

    Do you know why?

    Thanks for your help.

  2. JaZahn says:

    both code examples depend on you sending the smarty template $question_ids_json = [“1″,”2″,”3″,”4″,”5”];

    That’s probably the problem you’re having.

  3. Omar says:

    Thanks that’s work good.

  4. Manan says:

    thanks it works

Leave a comment