Partials vs blocks

Hey all,

I think partials and blocks have quite a bit of overlapping functionality. So my question is: in which situations would I use one over the other?

I’m sort of looking for pros and cons on partials and blocks.

I’ve been looking at some recent themes by @digitalcraftsman and most of them use partials most of the time. Would you say that blocks are a feature that’s been sort of deprecated in favor of partials? If so: is there a reason for this?

Thanks!

3 Likes

No.

Block templates were introduced in Hugo 0.16 after partials.

It’s a way to make your Hugo project templates adhere to the DRY (Don’t Repeat Yourself) principle.

Blocks can be used side by side with partials but the one does not exclude or supersede the other. Using blocks or partials is a matter of personal preference.

This is also the case for partials right?

Yeah I’ve seen that they can be used side by side and that both work.

I understand personal preference comes into play when we look at the overlapping functionality of blocks and partials. But they do differ functionally, right? If so: in what way?

1 Like

It depends on what you’re trying to do. I’ve seen cases where partials are not enough to avoid duplication and Blocks are the way to go.

Well in Block templates you typically have something like {{ block "main" . }} {{ end }} under layouts/_default/baseof.html and then you can define what the main block contains as many times as you need in various templates.

With Partials you need to provide alternate templates and that might end up not being very DRY (but again it depends on what one tries to do).

3 Likes

I use it this way: Block Templates (baseof.html) for the frame which goes around every page (like <head> and <body> with dynamic classes). And then partials for the individual parts of the page. I use more than on baseof.html.

Hope this helps.

2 Likes

If you have a template with opening tags and then some fillable content and then closing tags, it should be a block, not a pair of partial.

E.g. Don’t do this:

single.html:

{{ partial "header.html" . }}
<h1>My content</h1>
{{ partial "footer.html" . }}

header.html:

<html>
<body>

footer.html:

</body>
</html>

Do this instead:

baseof.html:

<html>
<body>
{{ block "main" . }}{{ end }}
</body>
</html>

single.html:

{{ define "main" }}
<h1>My content</h1>
{{ end }}

The reason is you’re not going to have a good time balancing tags between separate files, and as you have more place in your template to override (like the title, extra header bits, extra footer bits), it becomes impossible to keep track of which partials to include and in what order.

9 Likes

Ahhh yeah, that is a good reason. Thanks!