July 21, 2020

Add custom css and js to hugo page

So you have a hugo page or blog post, and you want to add some css or javascript just for that page, below is a way to do that.

Introduce front matter

Please follow this link where I found this suggestion which is kind of neat.

A front matter in hugo is the top part of the .md files. Here you can assign your own parameters that can be used withing your html templates in hugo.

Example of a front matter

--- 
title: My title 
js:  https://cdnjs.cloudflare.com/x.js 
css:  https://cdnjs.cloudflare.com/x.css 
---

In the above example title is a build i front matter in hugo, but both js and css is user defined front matters.

To be able to dynamically inject the suggested js and css front matters add below code to your page template.

Suggestion is to add the css and javascript to your layouts/partials/header.html template.

{{ if .Params.css }} 
<link rel="stylesheet" href="{{ .Params.css }}"> 
{{ end }}
{{ if .Params.js }}
<script src="{{ .Params.js }}"></script>
{{ end }}

The above code is simple as the if statement only adds the script/stylesheet if .Params.js or .Params.css is existing in the .md front matter.

Example

So lets add ace editor to this post. Add front matter for the ace editor javascript file:

js: https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.min.js 

Add the div editor and the settings for the ace editor. How to add raw html to .md files can be found in Add raw html support for hugo md files

<div id="editor" 
style="height: 250px; width: 500px">function foo(items) {
    var x = "All this is syntax highlighted";
    return x;
}</div>
<script>
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.session.setMode("ace/mode/javascript");
</script>
{{< /rawhtml >}}

And the rendered result is a bootstrap button below.

function foo(items) { var x = "All this is syntax highlighted"; return x; }

comments powered by Disqus

© Anis Alekic 2020