inline javascript within handlebars template

Rajat picture Rajat · May 3, 2012 · Viewed 9.1k times · Source

Is there no way to have an inline script within a Handlebars template?

<script type="text/x-handlebars">
    I'm a row of type "foo"
    <script type="text/javascript">alert('hi');</script>
</script>

When the above template renders, the inline script is removed.

What I am trying to do is include the disqus widget on a page. The widget is basically some markup + disqus script.

The widget is to be included within a sub-view of my app. The subview is not visible by default but is displayed as per some logic in my Ember app code. ​

Answer

Christopher Swasey picture Christopher Swasey · May 3, 2012

You'll have to wrap that widget in a custom Ember.View to handle instantiating it and adding it to the DOM, in the wrapper view's didInsertElement. Ember expects, especially inside handlebars templates, to have full control over DOM manipulation, and it does that with a combination of handlebars magic, and Ember.View creation. Once you've defined your customview:

MyApp.DisqusView = Em.View.extend({
    didInsertElement: function() {
        // create widget and append it to this.$()
    }
});

You can use it in your handlebars template:

{{view MyApp.DisqusView}}

Your view should not add Script tags, for safety reasons, but should rather execute any JS directly to insert the widget.