[Solved] Adding class attribute to <p> tags in {{ .Content }}

I need to add a class attribute to all of the

tags generated in the content of a page.

I have read the threads about using shortcuts, etc. I want to keep the markdown clean.

How can I set this up?

Randy

1 Like

Sounds like you want replace or https://gohugo.io/functions/replace/ replaceRE https://gohugo.io/functions/replacere/

Do you mean, “add class attributes”? Because if you need to add “a class”, you already have that behavior by default.

That you for the follow up.

If I have the following “content”:

+++
-- various --
++++

This is a paragraph

This is another paragraph

The output I desire for {{ .Content }} is:

<p class="mb4 px3">
This is a paragraph
</p>

<p class="mb4 px3">
This is another paragraph
<p>

I could author the markdown with the

<p class="mb4 px3"> 

in the markdown but I want non-technical people to write their own content.

What I am wondering is how can I augment the

wrappers for the paragraphs of {{ .Content }}.

Randy

1 Like

I hope someone has a solution for ya. In the meantime, why are you adding those to all the paragraphs?

I am building AMP pages and that specification severely restricts the amount of CSS you can specify. In particular I am using AMP start which has a version of http://basscss.com/. To get the formatting I want in the content section each

tag needs those class specifications.

You could run .Content through replaceRE (and safeHTML):

{{ .Content | replaceRE "<p>" "<p class=\"mb4 px3\">" | safeHTML }}
8 Likes

Thank you! Excellent solution

If someone comes here like me looking for a solution to add a class just for some paragraphs (or anything else) and not all of them, the best way I found is to create a file “layouts/shortcodes/class.html” with the following content:

<span class="{{ .Get 0 }}">
{{ .Inner }}
</span>

Then in your markdown use the shortcode like this:

{{% class yourClass %}}
your content
{{% /class %}}

Make sure there is an empty line above the shortcode. Otherwise it does not work. All the markdown for what is written inside will work as normal.

2 Likes

to extend @junedev - this won’t work anymore due to changes; https://gohugo.io/content-management/shortcodes/#shortcodes-with-markdown

Therefore add this line:

{{ $_hugo_config := `{ "version": 1 }` }}
<span class="{{ .Get 0 }}">
{{ .Inner }}
</span>

Still works great.

2 Likes