Skip to content

text/template: {{block}} in text/template #3812

@moraes

Description

@moraes
If you think this is worth a try, I can provide a initial implementation.

(this is not a defect, but a proposal/feature request)

We can achieve what is known as "template inheritance" in other template
engines using a new `{{block}}` tag (see:
https://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance). Hold on,
this proposal is not for real inheritance, this is really composition and I believe it
is better.

A `{{block}}` is a replaceable fragment inside a template. Here's an example:

{{{
    {{define "Base"}}
      <p>A header</p>

      {{block body}}
        <p>A body</p>
      {{end}}}

      <p>A footer</p>
    {{end}}}
}}}

The "body" block is executed normally when this template is called
directly. But when it is called by another template, the blocks
defined in the caller template receive higher priority and can
override the ones from the callee. Here is a template
that "extends" the previous template, overriding the "body" block:

{{{
    {{define "Page"}}
      {{block body}}
        <p>Another body</p>
      {{end}}

      {{template "Base" .}}
    {{end}}
}}}

When the "Page" template is executed, it calls the "Base" template
and its own "body" block overrides the original one.

This is even better than inheritance because you are not restricted
to a single parent template: you can compose multiple calls to other
templates, possibly overriding "blocks" from any of them.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions