Use 'with' along with 'block'

I’d like to have some code added around every ‘main_header’ block, except when it is not defined:

{{ with block "main_header" }}
  <div class="my header">
  {{ . }}
{{ end }}

However, that is not a supported syntax. Instead, I am using:

{{ block "main_header" . }}{{ partial "main_header.html" . }}{{ end }}

where main_header.html contains:

  <div class="my header">
  {{ block "main_header_content" . }}{{ end }}

As a result, I need to define main_header_content in the layouts where I want the header displayed; and add {{ define "main_header" }}{{ end }} in all the layouts where I don’t want the div to be added, because there is no main_header.

Is there any trick to avoid creating main_header.html and have the div defined in the base layout?

I think you can do what you want, without blocks. How about making the partial conditional, and including everything inside the partial (such as the div)?

At what level do you want to do this? Per section, content file, page or taxonomy?

I’d like to avoid defining the partial, in order to have the general layout defined in the baseof.html file. Partials are should be used to define content constrained by the general layout.

For every content. This is _default/baseof.html:

    <div class="outline w-100 ph2 pv4 mb0">
      {{ block "header" . }}{{ partial "header.html" . }}{{end}}
    <div class="flex">
      <div class="outline w-25 pa3 ma0">
        {{ block "sidebar" . }}{{ partial "sidebar.html" . }}{{ end }}
      <main role="main" class="outline w-75 pa0 ma0">
        {{ block "main_header" . }}{{ partial "main_header.html" . }}{{ end }}
        <div class="w-100 pa3 ma0">
        {{ block "main" . }}{{ end }}
    <div class="outline w-100 ph2 pv3 mt0">
      {{ block "footer" . }}{{ partial "footer.html" . }}{{ end }}

Then, in some sections (and the single pages in them) I don’t want main_header. In others, I want it shown in the single pages, but not in the pages list. Last, sometimes I want it shown in the list and page layouts.

How complex is your site? Are we talking about lots of sections and thousands of content pages?

If yes, you should stick with what you have.

But if your site is not that big you could assign a front matter parameter in content files, sections’ and pages where you want the main.header displayed. Then you can render it only on those pages using a simple with function based on that front matter parameter.

I see. Thanks for the suggestion. The site is not that big now, but it is expected to get bigger. Therefore, I’ll stick to the current solution.

Do you think it is worth opening an issue to request with being compatible with block as an enhancement?

You can try opening a Github issue see what the Devs think about a feature like this.