RejectedSoftware Forums

Sign up

Passing variable to JS

I have a JSON variable that I'm wanting to pass to javascript in a diet template.

:javascript
     var obj=JSON.parse(#{info});

When I load the website and check the page source there, it just copied "#{info}" into the source rather than loading the JSON string from the variable.

So, the source shows:

<script type="application/javascript">
     //<![CDATA[
          var obj=JSON.parse(#{info});
     //]]>
</script>

How can I extract the JSON string from the variable, as the method I use when working with D inside a template appears to function differently within a javascript filter.

Re: Passing variable to JS

On Sun, 10 Apr 2016 02:49:41 GMT, Chuck wrote:

I have a JSON variable that I'm wanting to pass to javascript in a diet template.

:javascript
     var obj=JSON.parse(#{info});

When I load the website and check the page source there, it just copied "#{info}" into the source rather than loading the JSON string from the variable.

So, the source shows:

<script type="application/javascript">
     //<![CDATA[
          var obj=JSON.parse(#{info});
     //]]>
</script>

How can I extract the JSON string from the variable, as the method I use when working with D inside a template appears to function differently within a javascript filter.

Unfortunately filters don't support string interpolations (due to logical compiletime-runtime conflicts). You can use a manual script tag, though. If your variable is already valid JSON (either a string or a Json value), you could also skip the JSON.parse step:

script.
    var obj = !{info};