HUGO

How to compare .Type value using if conditional? Or show code based on the page's content type?

Hi.

I wanted to display meta tag only for a specific page type. I referenced Hugo Docs and there’s a variable called .Type which can tell you the page type according to the folders in the content directory.

However, the following code gives me error:

{{ if eq .Type "essays" }}
<meta name="twitter:creator" content="@{{ . }}"/>
{{ end }}
Error: Error building site: failed to render pages: render of "page" failed: execute of template failed: template: _default/single.html:5:8: executing "_default/single.html" at <partial "head.html" .>: error calling partial: execute of template failed: template: partials/templates/twitter_cards.html:33:9: executing "partials/templates/twitter_cards.html" at <.Type>: can't evaluate field Type in type string

I am new to Hugo. Any help would be highly appreciated.

How are you calling the partial? Show the code.

I was actually overwriting PaperMod theme’s Twitter Cards template since .Site.Authors doesn’t work.

{{- template "partials/templates/twitter_cards.html" . }}

The above code is in the partial head.html which is called as the following in the default baseof.html as:

<head>
    {{- partial "head.html" . }}
</head>

Can you share your repository? It would make troubleshooting a lot easier.

How do I do that? Just share a link of the public github repo?:sweat_smile:

Yes…

Here’s the link. I am no professional though.
https://github.com/cryptic-code/hugo1

git clone --recurse-submodules https://github.com/cryptic-code/hugo1
cd hugo1
hugo
Start building sites … 

                   | EN  
-------------------+-----
  Pages            | 23  
  Paginator pages  |  0  
  Non-page files   |  0  
  Static files     |  8  
  Processed images |  0  
  Aliases          |  3  
  Sitemaps         |  1  
  Cleaned          |  0  

Total in 82 ms

Not sure what the problem is…

You have a scope/context problem.

{{ with .Site.Social.twitter -}}
<meta name="twitter:site" content="@{{ . }}"/>
  {{ if eq .Type "essays" }}
  <meta name="twitter:creator" content="@{{ . }}"/>
  {{ end }}
{{ end -}}

Read:

Two possible solutions:

{{ $type := .Type }}
{{ with .Site.Social.twitter -}}
<meta name="twitter:site" content="@{{ . }}"/>
  {{ if eq $type "essays" }}
  <meta name="twitter:creator" content="@{{ . }}"/>
  {{ end }}
{{ end -}}
{{ with .Site.Social.twitter -}}
<meta name="twitter:site" content="@{{ . }}"/>
  {{ if eq $.Type "essays" }}
  <meta name="twitter:creator" content="@{{ . }}"/>
  {{ end }}
{{ end -}}

Thank You So Much, Joe! You have been very helpful. :slight_smile:
I’m very much new to hugo. :sweat_smile: But this solved the problem.

1 Like

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