如何从gist中嵌入特定行?

26

Gist可以让你在网页中嵌入代码片段:

<script src="https://gist.github.com/dyoo/4627246.js"></script>

我希望能够只显示一个行范围子集。 (用例:在单个gist中为博客文章编写一些代码。在博客文章中引用某些行并讨论这些行。)

这可行吗? 我找不到官方文档,但有没有什么方法可以实现?


作为我认为它可能工作的示例,GitHub支持具有行号的URI。例如,此链接中的#L4-L8锚点:

https://github.com/twitter/bootstrap/blob/master/docs/base-css.html#L4-L8

我知道GitHub会显示所有的行,仅那些行高亮显示。而我想知道如何从一个Gist中显示特定的行。我提到这个只是举例说明,猜测它可能如何工作。


附言:根据如何使用新的Gist界面从GitHub Gist中嵌入单个文件?,似乎最近朝着相反的方向移动了:从一个gist中嵌入一个文件的能力最近消失了。我想要展示来自一个文件的某些特定行。但无论如何我都想问一下。此外,我认为这与之前的问题不同,这就是我发表新问题而不是在现有问题下评论的原因。


1
实际上,使用 ?file= 参数的旧方法仍然有效,但似乎不再在用户界面中实现。 - Adrian
3个回答

13

Gist API没有提供嵌入gist部分的方法。但是,您可以在自己的端口使用javascript来实现。

有一个不错的库可供使用:https://github.com/kashif-umair/gist-embed/

您可以使用此库来嵌入gist的部分内容。


1
这是 https://github.com/blairvanderhoof/gist-embed 的一个分支,定期更新并包含了许多其他功能。 - Abadaba
1
2014年6月15日:更新答案链接,指向基于过时分支的基础版本:https://github.com/kashif-umair/gist-embed/ - TomFuertes

3
你需要的是这个:

http://gist-it.appspot.com/


它是一个网站链接,可以用来分享代码片段。
# Embed the file robertkrimen/gist-it-example/example.js
<script src="http://gist-it.appspot.com/github/robertkrimen/gist-it-example/blob/master/example.js"></script>

# Embed without a footer
<script src="http://gist-it.appspot.com/github/robertkrimen/gist-it-example/blob/master/example.js?footer=0"></script>

# Show only the first and second line
<script src="http://gist-it.appspot.com/github/robertkrimen/gist-it-example/blob/master/example.js?slice=0:1"></script>

3

有一种方法可以在不使用库的情况下完成它

复制嵌入代码并将以下内容附加到src属性:?file=你的文件名


一个真实的例子

要点是 https://gist.github.com/dianjuar/8df3873cd9db49b7fcd86e74b57dd848

因此,为了仅在嵌入中显示名为circleci-useful-env-variables-pr.sh的文件,我必须

<script src="https://gist.github.com/dianjuar/8df3873cd9db49b7fcd86e74b57dd848.js?file=circleci-useful-env-variables-pr.sh"></script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接