3

I am really starting with Smarty and I do not understand this fact:

if I put the next code inside my template index.tpl

<script type="text/javascript">
  function toAlert() {
    alert('{$text}' );
  }
</script>

I can access to the function toAlert and show the content of Smarty variable {{$text}}, but if I put this code into a js file lije javascript.js and I try to access it by putting into de template the link:

I cannot access to the function as well.

Can anyone tell me why or help wher can I find this specific info? thank you!!

3
  • 2
    php executes before the page is loaded, so the js above actually looks like alert('theactualvalueof$text');. Therefor it cant work the other way arround, as php has already beed parsed when js runs Commented Jul 15, 2014 at 15:32
  • What I finally did was to load the PHP texts n the javaScript variables in the temaplate, like this: var text = '{$text}'; and then I could use the javascript variable text inside the <script> file loaded after the PHP code. Commented Nov 6, 2014 at 16:20
  • Yes, thats a good solution. Storing them as properties of an object instead of individual variables might be a little cleaner, eg var data = { text: '{$text}', other: '{$other}'}; Then you can access alert(data.text + ' ' + data.other); Commented Nov 6, 2014 at 16:30

2 Answers 2

4

Smarty 2 requires escaping of the "{" and "}" characters, you can use {ldelim} and {rdelim} to escape them individually or wrap entire blocks of text with {literal}{/literal}. It's usually cleaner to use {ldelim} and {rdelim} when there is embedded smarty tags, so example:

<script type="text/javascript">
  function toAlert() {ldelim}
    alert('{$text}');
  {rdelim}
</script>

Smarty 3 conveniently ignores "{" and "}" characters surrounded by white space, so your javascript example would work as-is.

Sign up to request clarification or add additional context in comments.

1 Comment

There is a typo in {redlim}. Should be {rdelim}.
3

You should put this code intp TPL file to make this work. Only TPL files are processed as Smarty files and you can use there Smarty variables.

Your code put should work out of the box in your index.tpl file but if it weren't try:

<script type="text/javascript">
{literal}
  function toAlert() {
    alert('{/literal}{$text}{literal}' );
  }
{/literal}
</script>

1 Comment

You are putting wrong '/' in alert literal <script type="text/javascript"> {literal} function toAlert() { alert('{literal}{$text}{/literal}' ); } {/literal} </script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.