1

In this code, I am trying to set the navbar and I am defining nav in each file because for some files, the navbar will log in or signup but for some files, it will be log out or about. No file is giving me errors except this login.html and the error is

Error

panic: template: login.html:7: unexpected <define> in command

code

{{template "base" .}}

{{define "title"}} Log In {{end}}

{{define "body"}}
    {{if .Loggedin}}
        {{define "nav"}}  // this is line 7 which is showing error.
            <div>
                <a href="/about">About</a>
                <a href="/logout">Logout</a>
            </div>
        {{end}}
    {{else}}
        <h1> Log In</h1>    
        <p>Login to access your account.</p>
        <hr>
        <form action="/loggedin" method="POST" name="login" id="login">
            <div>
                <label for="email">Email</label>
                <input type="email" name="email", placeholder="Enter your email address" required>
            </div>
            <div>
                <label for="password">Password</label>
                <input type="password" name="password", placeholder="Enter the password" required>
            </div>
            <div>
                <input type="submit" value="Login">
            </div>
        </form>
    {{end}}
{{end}}

1 Answers1

1

Quoting from package doc of text/template, Nested template definitions:

Template definitions must appear at the top level of the template, much like global variables in a Go program.

You can't define a template inside another template definition (and that's what you're doing).

Also note that {{define}} just defines a template, it does not include / execute it.

To define and execute a template in place, use {{block}}.

In your case move the template definition to the top level, and execute it where it's needed using the {{template}} action.

If you need different template definitions based on certain conditions, that's not possible.

What's possible is define different templates (with different names), and include the one you need based on the conditions.

Another option is to pass some data (the conditions) to the template, and make it render different things based on the template parameters (the conditions) with e.g. using the {{if}} action.

See related for even more options: How to use a field of struct or variable value as template name?

icza
  • 389,944
  • 63
  • 907
  • 827