How to apply Highlight.js to new views using Ember.js?

599 views Asked by At

I'm attempting to use highlight.js for syntax highlighting but can only get it to function on the first load.

The HTML:

<script type="text/x-handlebars" id="post">
 {{#if html}}
   {{rawhtml html}}
 {{else}}
   {{#each section}}
   {{rawhtml this}}
   {{/each}}
 {{/if}}
</script>

Using didInsertElement I am only able to get it to fire once.

App.PostView = Ember.View.extend({
  didInsertElement: function () {
    hljs.initHighlightingOnLoad();
  }
});

DEMO: http://jsbin.com/iKUrUWO/4 Go to Code, then 'CSS Best Practices'. Refresh your browser. Syntax highlighting will appear (pink and purple). Navigate to 'Naming Files' and back. Now the code is back to white.

JSBIN: http://jsbin.com/iKUrUWO/4/edit?html,js

Note: I attempted using a blockless form of the {{each}} helper but was not suscessful.

<script type="text/x-handlebars" id="post">
 {{each controller postViewClass="App.PostView"}}
</script>

App.PostView = Ember.View.extend({
  template: Ember.Handlebars.compile('{{#if html}}{{rawhtml html}}{{else}}{{#each section}}{{rawhtml this}}{{/each}}{{/if}}'),
    didInsertElement: function () {
      hljs.initHighlighting();
    }
  });

And for some reason can not use this.$().hljs.initHighlighting();.

I'm starting to get confused so any help would be appreciated! Thanks!

2

There are 2 answers

0
FellowMD On

I think the issue here is that ember code doesn't mix well with 'jquery plugin' style code. It looks like highlight.js has synchronous functions available that just take some code and mark it up with correct highlighting hljs.highlightAuto('code')

I'd try to create a highlight handlebars helper that processes text with the hljs function like:
{{highlight model.html}}

0
Steve H. On

I think for this you want to use a computed property. Simply define a function that returns the correct value followed with the .property extension in your "Post" class:

htmlContent: function() {
    var html= this.get('html');
    if (blah blah blah) {
        // do what you need to do to return the new content
    }
    return newValueToDisplay;
}.property('html')

Then just put this in your template: {{{htmlContent}}}

You say you can't use this.$().hljs.initHighlighting();, but you don't say why? Message in the console?