I want to write a similar named block in mako template. I know the basic templ" /> I want to write a similar named block in mako template. I know the basic templ" /> I want to write a similar named block in mako template. I know the basic templ"/>

Add attributes to named blocks in mako templates

113 views Asked by At

For a meta tag like:

<meta name="description" content="Sample Content">

I want to write a similar named block in mako template. I know the basic template format:

<%block name="meta"></%block>

I want to understand how to add the content attribute and its value in this named block.

1

There are 1 answers

0
Ian Wilson On BEST ANSWER

I don't think named blocks can really take arguments unless it is a page argument which doesn't seem to match this use-case very well. They are in the documentation.

You could use a function like this but the verbosity almost defeats the purpose:

<%def name="meta(name, content)">
<meta name="${name}" content="${content}">
</%def>

${render_meta("description", "Sample Content")}

In my layout, base, template I usually group the typical meta tags together in a single function and pass in the common arguments there.

<!DOCTYPE html>
<html lang="en-us" class="ma0 h-100-ns">
    <head>
        <%def name="head_meta(title=u'', description=u'', keywords=u'')">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        %if title:
        <title>${title}</title>
        %endif
        %if description:
        <meta name="description" content="${description}">
        %endif
        %if keywords:
        <meta name="keywords" content="${keywords}">
        %endif
        <meta name="viewport" content="width=device-width, initial-scale=1">
        </%def>
        ${self.head_meta()}
    </head>
<body>
## ....
</body>
</html>

Then in an inheriting template I might extend head meta to explicitly set title:

# -*- coding: utf-8 -*-
<%inherit file="/layout.mako"/> \
<%def name="head_meta()">
    ${parent.head_meta(
    title="Account")}
</%def>