Embedding a script with a jsrender template
Asked Answered
R

1

12

I would like to use a variable from my jsrender template in order to produce a snippet of javascript, but I can't figure out how to place a <script type="text/javascript"> within my <script id="data-item-tpl" type="text/x-jsrender">

Hopefully the below is fairly clear. The below code produces an Uncaught SyntaxError. If I remove the tags from the embedded script, then it is simply printed onto the page as text.

In the code below, I am trying to generate a div with the id 'chartId', and then a script which will fill that div with content, via the MyChart object.

<script id="data-item-tpl" type="text/x-jsrender">
    <div class="item">
        <div class="graphs">
            <ul class="thumbnails">
                {{for graphs}}
                <li><div class="thumbnail"><img src="{{html:url}}" width="190" height="120" /><p>{{html:graphTitle}}<br />{{html:value}}</p></div></li>
                {{/for}}
                <!-- Here we insert both the placeholder for, and the javascript to populate charts -->
                <li><div id="{{html:chartId}}" style="width:120;height:190px;"></div></li>
                <script type="text/javascript">
                    var chartObj = new MyChart("{{html:chartId}}");
                    chartObj.render();
                </script>
            </ul>                           
        </div>
        ...
</script>
Rolle answered 27/7, 2012 at 13:58 Comment(0)
R
13

I just did a little playing around and was able to get it working like this:

{{:"<scr" + "ipt type=&quot;text/javascript&quot;>"}}
    var chartObj = new MyChart("{{html:chartId}}");
    chartObj.render();
{{:"</scr" + "ipt>"}}

Maybe not the most elegant solution, but when I put an alert in there, it fired.

Rigatoni answered 27/7, 2012 at 16:23 Comment(2)
Yep! That's the kind of code-quality that everyone who writes web code has to live with pretty often. Web technologies suck. Period. Thanks!Claman
I am getting "Too many illegal characters" error in watch window. I couldn't use it.Gunzburg

© 2022 - 2024 — McMap. All rights reserved.