13

问题

我正在构建一个以minima为主题的 Jekyll 网站,以在线发布一些教程。教程页面包含许多代码片段,例如:

```javascript
/* Global scope: this code is executed once */
const redis = require('redis');

const host = <HOSTNAME>;
const port = <PORT>;
const password = <PASSWORD>;

...
```

我想为每个代码片段(示例)添加一个“复制到剪贴板”按钮,但不确定在 Jekyll 中执行此操作的正确方法是什么。

我试过什么

  • 使用clipboardjs.com。每个片段都需要一个唯一的 ID,我不确定如何在 Jekyll/Markdown 中实现它。
  • STFW

我的问题

如何在 Jekyll 中为代码片段添加“复制到剪贴板”按钮?

4

2 回答 2

5

使用 kramdown 的Block Inline Attribute Lists为每个代码块手动生成 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>

使用 jQuery

代码块使用codehtml 元素,如果我们检测到它,则我们加载 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');
<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>

于 2018-01-03T13:54:54.283 回答
1

让我们使用包含

教程.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>
于 2018-01-10T07:33:05.240 回答