gohugoio / hugo

The world’s fastest framework for building websites.
https://gohugo.io
Apache License 2.0
76.09k stars 7.54k forks source link

A way for a template (e.g. single.html) to signal a flow in the base template #11023

Open bep opened 1 year ago

bep commented 1 year ago

The files in the PR in #11024 is a technical way of implementing this in the templates today (we could consider adding some built-ins for this if needed). Those file don't demonstrate "how useful" this is, but I will talk a little about that below.

-- hugo.toml --
-- content/_index.md --
-- content/p1.md --
-- layouts/_default/baseof.html --
{{ block "_baseof_start" . }}{{ end }}
<html>
<head>
{{/* Lots of imports of SEO partials, stylesheets, JS and whatnot. */}}
</head>
<body>
{{ $flow := .Store.Get "_baseof_flow" | default "default" }}
{{ if eq $flow "default" }}
    <div>
    <h1>Default flow</h1>
    {{ block "main" . }}{{ end }}
    </div>
{{ else if eq $flow "foo" }}
    <div>
        <h1>Foo flow</h1>
        {{ block "main" . }}{{ end }}
    </div>
{{ else if eq $flow "bar" }}
    <div>
        <h1>Bar flow</h1>
        {{ block "main" . }}{{ end }}
    </div>
{{ end }}
</body>
</html>
-- layouts/index.html --
{{ define "_baseof_start" }}{{ .Page.Store.Set "_baseof_flow" "foo" }}{{ end }}
{{ define "main" }}Main Home{{ end }}
-- layouts/_default/single.html --
{{ define "_baseof_start" }}{{ .Page.Store.Set "_baseof_flow" "bar" }}{{ end }}
{{ define "main" }}Main Single{{ end }}

In many sites, even bigger ones, you end up wanting to have only one baseof.html template. You can of course create several templates and avoid some DRYness by adding the common pieces via partials, but it can still be a hassle if only small parts of your base template changes.

The tooling you have for this today are:

But there are often subtle structural difference in the different layouts (e.g. grid layouts, table of contents), which leads to either

The above construct may help simplify things, and it could also be a way to pass data up to the base template.

davidfmiller commented 1 year ago

I have just encountered a situation where I would like to be able to modify which baseof.html is used for a specific content type based on the value in an environment variable... this change/issue would permit that setup? ❤️