2018年11月14日 星期三

Using marked.js with hightlight.js in rails to provide github flavored markdown to github style html


In this example, I use webpacker to import highlight js and marked js and css file, you can use cdn as well.



`app/javascripts/application.js`
```js
import marked from 'marked';
import hljs from 'highlight.js';

marked.setOptions({
  highlight: function(code) {
    return hljs.highlightAuto(code).value;
  },
})

window.marked = marked
```

Let's say we have Post model with `content` field with markdown text

`app/views/posts/show.html.erb`

```erb
<h1><%= @post.title %></h1>

<%= @post.user.email %> - <%= @post.created_at %>

<div id="postContent">
  <%= @post.content %>
</div>

<%= content_for :javascripts do %>
<script>
  var contentElement = document.querySelector('#postContent')
  contentElement.innerHTML = marked(contentElement.innerHTML)
</script>
<% end %>
```

And add application.js into layout by adding this line into `app/views/layout/application.html.erb`

```erb
<%= javascript_pack_tag 'application' %>
```

Now marked.js and hightligh.js are both working properly, check the HTML DOM on post page and you'll see html elements with some auto generated css classes.

However, it's not showing the right styles because we only apply JS but not CSS, now what we need to do is add github style which is provided by highlight.js.

In my other post I've shown how to add it: https://everyday1percent.blogspot.com/2018/11/import-css-from-npm-module-in-rails.html

In `app/javascripts/styles.js`

```js
import 'highlight.js/styles/github.css';
```

And then add to layout

```erb
<%= stylesheet_pack_tag 'styles' %>
```

And that's it, now the Post show page will show markdown text in HTML format with github styles.

Cheers.


https://github.com/highlightjs/highlight.js/issues/578
https://marked.js.org/#/USING_ADVANCED.md#highlight
https://everyday1percent.blogspot.com/2018/11/import-css-from-npm-module-in-rails.html

沒有留言:

張貼留言