如何在 Rails 中使用 highlight.js? [英] How to use highlight.js with Rails?

查看:61
本文介绍了如何在 Rails 中使用 highlight.js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 rails 应用程序中使用 highlight.js 的语法高亮.highlight.js 的说明如下(https://github.com/isagalaev/highlight.js):

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):

在网页上使用 highlight.js 的最低要求是链接到库以及其中一种样式并调用 initHighlightingOnLoad:

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>

我不确定上面三个应该放在哪里.我已经尝试了几种可能性.大概是三个中的第一个,<链接rel ... >,应该放在views/application/application.html.erb的头部.我认为这三个中的第二个,<script src=... >, 应该放在包含将突出显示的代码的文件的底部.我认为三个中的第三个,<脚本 ... >,应该放在 application.js 文件中.无论如何,我已经尝试了这个和其他几种可能性,但我一直无法在 Ruby 中突出显示所需的代码.

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.

推荐答案

为我工作..

创建一个文件复制 app\assets\stylesheets\github.scss(github.scss 或您的偏好样式,https://highlightjs.org/static/demo/).不要忘记 import @import "github"; 到你的文件 app\assets\stylesheets\application.scss

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

创建一个文件 app\assets\javascripts\highlights.js,并复制下面的代码

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

如果您使用 turbolinks:

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.

这篇关于如何在 Rails 中使用 highlight.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆