Search code examples
csstailwind-csshugo

How do you add a CSS class to a paragraph in Hugo


I am new to Hugo, and I've been trying for over 30 minutes to get a class on a paragraph, but it isn't having it.

I am using TailwindCSS and I need to add some css classes to the paragraph tag.

CODE:

In my .md file I have

This is some paragraph text.
{.font-normal .text-lg}

According to the docs (scroll down a little bit) the above should work, but I get:

<p>This is some paragraph text.
{.font-normal .text-lg}</p>

What I actually want is:

<p class="font-normal text-lg">This is some paragraph text.</p>

What am I doing wrong? hugo version gives me hugo v0.105.0+extended linux/amd64 BuildDate=unknown


Solution

  • [Edit] My original answer appears below, but here's a better answer for anyone else who runs into this issue.

    Hugo uses Goldmark to parse markdown, and by default it sets markup > goldmark > renderer > unsafe to "false." This means that if you mix HTML in with your markdown, hugo will throw an error instead of rendering the HTML.

    If you change the "unsafe" setting to "true," hugo will render your HTML. You make this setting in your config.yaml file (or config.toml or config.json, whichever you're using). For info on how to apply this setting, see https://gohugo.io/getting-started/configuration-markup/#goldmark.

    Note that when unsafe=true, you can break your page layout if you write bad HTML. Typically, though, you just want to throw in something like [div class="whatever"][/div]. Most people are smart enough not to screw that up.

    [Original Response] This is actually kind of a pain in the ass. You need to create your own shortcode. In your Hugo project directory, create a file called attr.html in the following location:

    /layouts/shortcodes/attr.html

    Then put this in attr.html:

    <p
        {{ if .Get "class"}}class="{{ .Get "class" }}"{{ end }}
        {{ if .Get "id" }}id="{{ .Get "id" }}"{{ end }}
        {{ if .Get "name" }}name="{{ .Get "name" }}"{{ end }}
        {{ if .Get "style" }}style="{{ .Get "style" }}"{{ end }}
    >{{ .Inner }}</p>
    

    Then, going back to your markdown file, do this:

    {{< attr class=".font-normal .text-lg" >}}This is some paragraph text.{{< /attr >}}
    

    You should end up with this output:

    <p class=".font-normal .text-lg">This is some paragraph text.</p>
    

    The shortcode above supports id, name, and style attributes as well. If you need more, you'll have to add them to the shortcode template. Also note that this template assumes you want "p" tags in your output.