A way to mark plain-text and stop hugo from interpreting?


Hi guys,
I recently came upon a tricky scenario where I need to mark a block as plain-text and prevent hugo from interpretting it.
Eg, say we have defined a shortcode “code” for highlighting some code block. The following is the definition

<pre class="prettyprint lang-{{ .Get 0 }}"> {{ .Inner }} </pre>

Then we want to use it to highlight a block of hugo code:

{{< code "html" >}} 
 <pre class="prettyprint lang-{{ .Get 0 }}"> {{ .Inner }} </pre> 
{{< /code >}}

Now, before passing the inner content to the .Inner variable, hugo first tries to interpret the content as code which of course will lead to problem.

I’m thinking about some way to inform hugo that this piece of content is plain-text and should not be interpreted, any ideas? Thanks.


What do you want Hugo to generate?

Since you’re using the {{< >}} syntax, Hugo will pass everything in the body through unmodified, as raw HTML.
So, the example you posted will (correctly) generate:

<pre class="prettyprint lang-html"> <pre class="prettyprint lang-{{ .Get 0 }}"> {{ .Inner }} </pre> </pre>

The inner <pre ... won’t be visible in a browser, since the browser interprets it (correctly) as a tag.

If you want <pre ... to be displayed in the browser, you can change your shortcode slightly:

<pre class="prettyprint lang-{{ .Get 0 }}"> {{ printf "%s" .Inner }} </pre>

.Inner is a template.HTML (a type), which basically means that Go’s template library won’t worry about escaping it. The printf "%s" .Inner transforms .Inner into a regular string, so the template library does escape it. (For the inverse, see safeHTML in the Hugo docs, under Templates > Functions)

The updated shortcode produces something like

<pre class="prettyprint lang-html"> 
&lt;pre class=&#34;prettyprint lang-{{ .Get 0 }}&#34;&gt; {{ .Inner }} &lt;/pre&gt; 

which is probably more what you wanted.

Other notes:

  • You may want to explore using fenced code blocks, which can indicate the language used. See “Fenced Code Blocks” on the Blackfriday page. They produce <pre><code class="language-html"> ... </code></pre>
  • If you want to talk about shortcodes, there’s a(n apparently undocumented) way to escape the shortcode processing: {{</* code */>}} will be passed through as {{< code >}} and will not be processed. See the source of the Hugo template function docs for example usage.


@lotrfan Thanks for the detailed explanation, I tested and your suggestion of using “printf” is exactly what I wanted, thanks a lot.


It is undocumented, yes. Documenters welcome! I added it to be able to document the shortcodes and the syntax is very similar to Go’s text template comments.