How to display the html-tag through the condition if hugo?

Hi. I have a code in the hugo template engine that should add a script if the parameter in the article is equal to the desired value.

Front Matter articles. Here I need the header_class parameter

---
title: "Replaced header"
header_class: "replaced-header"
---

If header_class = “replaces-header” output the code. I tried to implement it like this:

{{ if isset .Params.header_class "replaced-header" }}
<script>
    let replacedHeader = document.querySelector('.replaced-header');
    window.onscroll = function() {
        let breakPoint = 100;
        let scroll = window.pageYOffset || document.documentElement.scrollTop;
        if(scroll > breakPoint) {
            replacedHeader.classList.add('replaced-header--scrolled');
        }
    };
</script>
{{ end }}

The code doesn’t work. How should a condition be set in this case?

{{ with $.Param "replaced-header" }}

should work for you. Please note that the param INSIDE the with the parameter is a dot {{ . }}.

{{ with $.Param "replaced-header" }}
{{ . }}
{{ end }}

This code does not work

{{ with $.Param "replaced-header" }}
    {{ . }}
    <script>
        let replacedHeader = document.querySelector('.replaced-header');
        window.onscroll = function() {
            let breakPoint = 100;
            let scroll = window.pageYOffset || document.documentElement.scrollTop;
            if(scroll > breakPoint) {
                replacedHeader.classList.add('replaced-header--scrolled');
            }
        };
    </script>
    {{ end }}

And this one doesn’t work either

{{ with $.Param "replaced-header" }}
    <script>
        let replacedHeader = document.querySelector('.replaced-header');
        window.onscroll = function() {
            let breakPoint = 100;
            let scroll = window.pageYOffset || document.documentElement.scrollTop;
            if(scroll > breakPoint) {
                replacedHeader.classList.add('replaced-header--scrolled');
            }
        };
    </script>
    {{ . }}
    {{ end }}

I check in my browser in incognito mode.
Perhaps I am missing something?

Any of these three methods:

  {{ if isset .Params "header_class" }}
    {{ .Params.header_class }}
  {{ end }}

  {{ with .Params.header_class }}
    {{ . }}
  {{ end }}

  {{ with .Param "header_class" }}
    {{ . }}
  {{ end }}

Note that the last one will first look for the parameter in front matter, then in the site configuration. The second is the preferred method.

2 Likes

Your param is header_class, not the value of it.

{{ with $.Param "header_class" }}
{{ if ( eq . "replaced-header") }}
your header
{{ end }}
{{ end }}
1 Like

This works, thanks a lot!

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