hugo

How can I test for a literal string in Hugo front matter?


I want to know if the value of .field is the same as my string literal. What's the right syntax to do that?

{{ if .Params.field matchesText "random"}}
    <h1>Success!</h1>
{{ end }}

Obviously, I made up matchesText.

I found a function for containing strings in the Hugo docs, but that's not the same as comparing.


Solution

  • The in function

    {{ if in .Params.field "random"}}
        <h1>Success!</h1>
    {{ end }}
    

    The in function checks if an element is in an array, slice, or substring of a string. In some languages (e.g., Java), you have to worry about some comparisons failing because human-equivalent strings are not equivalent in memory. Thankfully, that's not problem with Hugo's in.