Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inline javascript within handlebars template

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. ​

like image 360
Rajat Avatar asked May 03 '12 10:05

Rajat


People also ask

Can you put JavaScript in Handlebars?

Handlebars. js is a Javascript library used to create reusable webpage templates. The templates are combination of HTML, text, and expressions. The expressions are included in the html document and surrounded by double curly braces.

How do partials work in Handlebars?

Partials are useful when you have a chunk of markup that you want to reuse in more than one place. A Handlebars partial is just a template that you can render inside of another template using the {{> partialName }} partial call syntax after registering it with Handlebars.

Should I use EJS or Handlebars?

EJS Is Way Faster Than Jade And Handlebars. EJS Has A Really Smart Error Handling Mechanism Built Right Into It. It Points Out To You, The Line Numbers On Which An Error Has Occurred So That You Don't End Up Looking Through The Whole Template File Wasting Your Time In Searching For Bugs.


1 Answers

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.

like image 88
Christopher Swasey Avatar answered Sep 20 '22 03:09

Christopher Swasey