Replace function when applied to .Content displays html tags instead of rendering them

Hi All,

I am trying to link keywords found in .Content with a link tag. When I used the replace function like below, the html tags are showing up as <p>hello</p> instead of rendering them.

{{ range $topics }}
    {{- if and (strings.Contains $.Content .) -}}
    {{ replace $.Content . "<a href='$Permalink'>.</a>" }}
    {{ end }}
{{ end }}

The above code makes $.Content an unrendered string. That is, instead of rendering the html content (which comes from markdown content files), it shows the actual tags like <h2><p> etc.

I have tried applying safeHTML like below, but it doesnt affect the output.

{{ $.Content | safeHTML }}

Is there a way to convert unrendered content to rendered content.

write it like this:

{{ $Content := .Content }}

{{ range $topics }}
    {{- if (strings.Contains $Content .) -}}
    {{ $Content = replace $Content . "<a href='$Permalink'>.</a>" }}
    {{ end }}
{{ end }}

{{ $Content | safeHTML }}
1 Like

Hi @pamubay

Thank you. Your fix worked and for the $permalink to make it dynamic I used the below

{{ $link := printf "%s" "</a>" | printf "%s%s" . | printf "%s%s" "'>" | printf "%s%s" $permalink | printf "%s%s" "<a href='" | printf "%s" }}

@bep have a question on the replace function. The current replace function replaces all occurrences of the search text. But is there a method that replaces only the first occurrence or a particular index of the occurrence. Sorry I did try looking into the documentation first, but I couldn’t find it.

you can set LIMIT parameter on replace, to replace first occurrence:

{{ replace "aaaa" "a" "b" 1 }} // => "baaa"

Not possible.

back on you “real” problem, the only solution i can think of:

  1. range the $topics, each iteration will execute replaceRE on Content with dynamic regex formula from current topic/word.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.