-1

I have observed that, while writing JS in script tags into the template will run the script, inserting them into the template using a Handlebars expression will prevent it from running.

I have tried writing this into my component:

test: Ember.String.htmlSafe("<script>console.log('Hello World')</script>")

And in my template:

{{test}}

This will insert it into the DOM, but will not run the code. I thought it was because HTMLBars did not allow script tags in the template, but just writing

<script>console.log('Hello World')</script>

into the template itself will run the JS within.

Can somebody tell me if there is a way to achieve this, or provide an explanation as to why this happens? Thanks in advance.

Jan
  • 1
  • 2

2 Answers2

0

If you work with javascript string you can use extra {{{ }}} to display them properly. Safe template output with:

{{{test}}}

That will do the job. Have a look at this blog post

http://www.kaspertidemann.com/html-safe-strings-in-handlebars/

Mirza Memic
  • 862
  • 5
  • 9
  • Thank you for the quick response. Using Ember.String.htmlSafe with the double brackets also gets around the escaping and displays them properly. The script tag appears just fine, but it is the JS within that does not run. I did also try the triple brackets just to check, and the JS does not run either. – Jan Jun 29 '16 at 18:40
  • 1
    I am not sure what you are trying to achieve? General in ember you can write a helper that does escape the string or use triple bracket. Do you want it to run the script since your question states that HTML.safe does not run? it should not run that is why it is safe lol – Mirza Memic Jun 29 '16 at 19:22
0

There is no need to do that. You can either run JavaScript code from your Component or have <script> tag in your template (like you've described in your question).

Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89