Forum Moderators: coopster

Message Too Old, No Replies

How to set Smarty variable inside Javascript?

         

toplisek

8:25 am on Apr 16, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There is solution to use {literal}{/literal} and in the middle of this Smarty variable.

Issue is how to solve double {{. Smarty variable is placed {$myvariable.name1} and also {$myvariable.name2}
Example of code:

{literal}
<script>
var google_custom = google_custom || {};
google_custom.visitor = {
{$myvariable.name1}: (window.google? google.get_cookie('{$myvariable.name2}'): '')
};
</script>
{/literal}

Need help.

whitespace

9:10 am on Apr 16, 2015 (gmt 0)

10+ Year Member Top Contributors Of The Month



Admittedly I'm not too familiar with Smarty, however, if this is purely a server-side templating engine (which I thought it was) then you can't "set a Smarty variable inside JavaScript" (which runs only on the client).

You can set a JavaScript variable inside Smarty (or rather, you can construct the JS that will ultimately run on the client inside Smarty), but not the other way round.

What is it you are trying to achieve?

toplisek

11:14 am on Apr 17, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It is actually not correct. If you try to put session variable inside Javascript you have to break Javacript using {literal} and finish {/literal}

So, when this breaks you can add Smarty variable. There is an issue that variable is not detected such as {$myvariable.name1}. It will be doubled.

Example:
{literal}
<script>
var google_custom = google_custom || {};
google_custom.visitor = {{/literal}
{$myvariable.name1}{literal}: (window.google? google.get_cookie('{/literal}{$myvariable.name2}{literal}'): '')
};
</script>
{/literal}

whitespace

12:37 pm on Apr 17, 2015 (gmt 0)

10+ Year Member Top Contributors Of The Month



Ahhh... ok... so, JavaScript doesn't really have anything to do with it?! You are trying to output (not set?) a Smarty variable inside a Smarty {literal}, but the double brace is an issue (yes, you did mention this, but it wasn't clear from your example)...

What about if you separate the braces with some whitespace? (no pun intended) For example:


google_custom.visitor = {
{/literal}
{$myvariable.name1}{literal}: (window.google ......


Or even include a harmless comment...


google_custom.visitor = { /* DO NOT REMOVE THIS COMMENT */
{/literal}
{$myvariable.name1}{literal}: (window.google ......

toplisek

9:49 am on May 18, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thank you. It works.