Given the following code:
$('img').mouseenter(function(){
//...
}).mouseleave(function(){
//...
});
I'd like it to be included in my articles. I'd like to avoid editing the theme if possible so to avoid forking etc.
Given the following code:
$('img').mouseenter(function(){
//...
}).mouseleave(function(){
//...
});
I'd like it to be included in my articles. I'd like to avoid editing the theme if possible so to avoid forking etc.
这在一定程度上取决于您使用的主题。这可能是我们可以做得更好的领域,但是这样做:
在主题中,查看
layouts/partials
文件夹。
如果您找到一个header.html
或类似的,请将其复制到您的本地layouts/partials
. 然后,您只能覆盖此文件的内容。或者,您可以通过复制用于单个页面的模板进行自定义,通常:layouts/_default/single.html
.
bep的回答非常好,但这里有一些额外的细节,供像我这样的 hugo/frontend 新人使用
首先,应该将 Hugo 主题的header.html
或footer.html
(或类似)复制到您的layouts/partials
文件夹中。它不一定是页眉或页脚,而是包含在 html 的每个页面中的文件(这就是您通常使用header.html
or的原因footer.html
)。
我得到了一个有页脚的主题,<theme_folder>\layouts\partials\_shared\footer.html
然后我将其从主题文件夹复制到项目布局文件夹<project_root>\layouts\partials\_shared\footer.html
中。
然后,我添加到底部footer.html
<script defer language="javascript" type="text/javascript" src="{{ "/js/myscripts.js" | urlize | relURL }}"></script>
defer属性可以稍微提高页面加载时间,并且"/js/myscripts.js"
是我的 javascripts 的位置。该位置是相对于 的路径<project_root>\static\
。这是关于relURL和urlize的文档。
示例脚本文件仅包含
// myscripts.js
function myFunction(x) {
let d = new Date();
alert("Current datetime: " + d + "\nYou passed in: " + x);
}
这是在 Hugo 模板(属于模板的任何 .html)中使用 JS 函数的示例:
{{ $somevar := "spam"}}
<button onclick="myFunction( {{ $somevar}} )">Click me</button>
看起来内联 JS 也运行得很好;例如,添加
<script>
alert("Script loaded!");
</script>
到模板 html 文件运行得很好。不过,我只会将其用于快速测试,因为多个 html 文件中可能需要一些脚本,并且将相同的脚本添加到多个文件只会增加您的整体网站文件大小。
我将主题/whatever/layouts/_default/baseof.html 复制到 layout/_default/baseof.html 并在 html 标记的末尾添加以下块:
{{ 块“页面脚本”。}}{{ 结尾 }}
然后我可以添加
{{- define "page-script" -}}
<script>console.log("Hello!")</script>
{{- end -}}
在我的布局文件中放入脚本。