How to use highlight.js with Rails?

半世苍凉 提交于 2020-01-04 11:19:27

问题


I am trying to use syntax highlighting with highlight.js in my rails application. The instructions for highlight.js are below (https://github.com/isagalaev/highlight.js):

The bare minimum for using highlight.js on a web page is linking to the library along with one of the styles and calling initHighlightingOnLoad:

<link rel="stylesheet" href="/path/to/styles/default.css">
<script src="/path/to/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

I'm not certain where the above three should be placed. I've tried several possibilities. Presumably the first of the three, < link rel ... >, should be placed in the head of views/application/application.html.erb. And I think that the second of the three, < script src=... >, should be placed at the bottom of the file that contains the code that will be highlighted. I thought the third of the three, < script ... >, should go in the application.js file. In any case, I've tried this and several other possibilities, but I haven't been able to get the desired code highlighted in Ruby.


回答1:


Worked for me..

  • Create a file copy app\assets\javascripts\highlight.pack.js (Find file content here: https://highlightjs.org/download/)

  • Create a file copy app\assets\stylesheets\github.scss (github.scss or your preference style, https://highlightjs.org/static/demo/). Don't forget import @import "github"; into your file app\assets\stylesheets\application.scss

  • Create a file app\assets\javascripts\highlights.js, and copy this follow code

If you are using turbolinks:

$(document).on("turbolinks:load", function() {
  $('pre code').each(function(i, block) {
    hljs.highlightBlock(block);
  });
});

If you are not using turbolinks:

$(document).ready(function() {
  $('pre code').each(function(i, block) {
    hljs.highlightBlock(block);
  });
});

And done. Restart your server.




回答2:


You can place highlight.pack.js right in your app/assets/javascripts folder. It will be loaded into the Rails Asset Pipeline from there.

You should place default.css in your app/assets/stylesheets folder. It will also be loaded into the Rails Asset Pipeline from there (note you might need to rename this file to default.css.scss) I am unsure of whether or not you'll have to add the .scss file extension (maybe someone can edit this answer if they know - for now, rename it to default.css.scss).

...and then you should add this to your app/assets/javascripts/application.js file

$(document).ready(function() {
  $('pre code').each(function(i, block) {
    hljs.highlightBlock(block);
  });
});

In your view file you can use this:

<pre><code>
  Ruby Code Goes Here
</code></pre>


来源:https://stackoverflow.com/questions/28574032/how-to-use-highlight-js-with-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!