Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding a script with a jsrender template

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>
like image 862
Ina Avatar asked Jul 27 '12 13:07

Ina


1 Answers

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.

like image 131
MrOBrian Avatar answered Oct 05 '22 02:10

MrOBrian