Template - Check if block is defined

Hi there,

right now I am looking around how to check if content for a particular block is defined. But by now I could not find anything. Does someone know a way to do this? sth. like

{{ if block "some_block" defined }}

1 Like

As far as I can tell there is no way to do this with the predefined actions.

However, I figured out how to do it with helper functions. Here is my test program and output. The results were different when using text/template and html/template, so I included results for both of them.

main.go

package main

import (
	"bytes"
	"fmt"
	"html/template"
	"log"
	"os"
)

const (
	block = `{{define "block"}}BLOCK{{end}}`

	templateBlock = `{{template "block"}}`

	check = `
{{if hasTemplate "block"}}
	{{template "block"}}
{{else}}
	block does not exist
{{end}}`

	ifExists = `{{templateIfExists "block" ""}}
after`
)

func main() {
	log.SetFlags(log.Lshortfile)

	fmt.Println("## templateBlock:")
	render(templateBlock)

	fmt.Println("\n## block + templateBlock")
	render(block + templateBlock)

	fmt.Println("\n## check without block")
	render(check)

	fmt.Println("\n## check with block")
	render(block + check)

	fmt.Println("\n## ifExists with block")
	render(block + ifExists)

	fmt.Println("\n## ifExists without block")
	render(ifExists)

	fmt.Println()
}

func render(text string) {
	tmpl := template.New("")
	tmpl = tmpl.Funcs(template.FuncMap{
		"hasTemplate": func(name string) bool {
			return tmpl.Lookup(name) != nil
		},
		"templateIfExists": func(name string, pipeline interface{}) (string, error) {
			t := tmpl.Lookup(name)
			if t == nil {
				return "", nil
			}

			buf := &bytes.Buffer{}
			err := t.Execute(buf, pipeline)
			if err != nil {
				return "", err
			}

			return buf.String(), nil
		},
	})

	tmpl, err := tmpl.Parse(text)
	if err != nil {
		log.Println(err)
		return
	}

	err = tmpl.Execute(os.Stdout, nil)
	if err != nil {
		log.Println(err)
		return
	}
}

using text/template

$ go run main.go
## templateBlock:
main.go:81: template: :1:11: executing "" at <{{template "block"}}>: template "block" not defined

## block + templateBlock
BLOCK
## check without block


	block does not exist

## check with block


	BLOCK

## ifExists with block
BLOCK
after
## ifExists without block

after

using html/template

$ go run main.go
## templateBlock:
main.go:81: html/template::1:11: no such template "block"

## block + templateBlock
BLOCK
## check without block
main.go:81: html/template::3:12: no such template "block"

## check with block


	BLOCK

## ifExists with block
BLOCK
after
## ifExists without block

after
2 Likes

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