我正在使用minima主题构建一个Jekyll网站,以在线发布一些教程。教程页面包含许多代码段,例如:
```javascript
/* Global scope: this code is executed once */
const redis = require('redis');
const host = <HOSTNAME>;
const port = <PORT>;
const password = <PASSWORD>;
...
```
我想将一个&#34;副本添加到剪贴板&#34;每个代码段(example)的按钮,但不确定在Jekyll中执行此操作的正确方法。
如何添加&#34;复制到剪贴板&#34; Jekyll中代码片段的按钮?
答案 0 :(得分:3)
使用kramdown&lt; 阻止内联属性列表为每个代码块手动生成ID,并在其后添加{: #code-example-1}
。
在你的例子中:
```javascript
/* Global scope: this code is executed once */
const redis = require('redis');
const host = <HOSTNAME>;
const port = <PORT>;
const password = <PASSWORD>;
...
```
{: #code-example-1}
这会产生:
<div id="code-example-1" class="language-javascript highlighter-rouge">
....
</div>
代码块使用code
html元素,如果我们检测到它,那么我们加载js,遍历添加自定义ID的所有代码元素,以及复制其内容的按钮。最后初始化剪贴板按钮。
{% if page.content contains "code" %}
<script>
<!-- clipboard.js code -->
</script>
{% endif %}
// get all <code> elements
var allCodeBlocksElements = $( "code" );
allCodeBlocksElements.each(function(i) {
// add different id for each code block
// target
var currentId = "codeblock" + (i + 1);
$(this).attr('id', currentId);
//trigger
var clipButton = '<button class="btn" data-clipboard-target="#' + currentId + '"><img src="https://clipboardjs.com/assets/images/clippy.svg" width="13" alt="Copy to clipboard"></button>';
$(this).after(clipButton);
});
new Clipboard('.btn');
&#13;
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/clipboard@1/dist/clipboard.min.js"></script>
<code>print("Club Nacional de Football")</code>
<br>
<code>print("is a sports institution")</code>
<br>
<code>print("from Uruguay")</code>
&#13;
答案 1 :(得分:1)
让我们使用includes。
<强> tuto.md 强>
---
front matter things here
---
{%- capture code -%}
/* Some js code */
const redis = require('redis');
const host = <HOSTNAME>;
{%- endcapture -%}
{% include code_snippet.md code=code language='javascript' %}
{%- capture code -%}
# Some ruby code
t = Time.now
t.succ
{%- endcapture -%}
{% include code_snippet.md code=code language='ruby' %}
<强> _includes / code_snippet.md 强>
{% assign code = include.code %}
{% assign language = include.language %}
``` {{ language }}
{{ code }}
```
{% assign nanosecond = "now" | date: "%N" %}
<textarea id="code{{ nanosecond }}" style="display:none;">{{ code | xml_escape }}</textarea>
<button id="copybutton{{ nanosecond }}" data-clipboard-target="#code{{ nanosecond }}">
Copy to clipboard
</button>
<script>
var copybutton = document.getElementById('copybutton{{ nanosecond }}');
var clipboard{{ nanosecond }} = new Clipboard(copybutton);
clipboard{{ nanosecond }}.on('success', function(e) {
console.log(e);
});
clipboard{{ nanosecond }}.on('error', function(e) {
console.log(e);
});
</script>