Skip to content

Instantly share code, notes, and snippets.

@morrelinko
Created November 22, 2017 16:29
Show Gist options
  • Save morrelinko/ec81c66667de6d0b27a2150160a669d9 to your computer and use it in GitHub Desktop.
Save morrelinko/ec81c66667de6d0b27a2150160a669d9 to your computer and use it in GitHub Desktop.
Nunjucks 'yield' Extension (One liner block expressions)
'use strict'
class YieldExtension {
get tags () {
return ['yield']
}
parse (parser, nodes, lexer) {
let tag = parser.nextToken()
parser.skipSymbol(tag.value)
let node = new nodes.Block(tag.lineno, tag.colno)
node.name = parser.parsePrimary()
node.body = new nodes.NodeList(0, 0, [new nodes.Output(0, 0, [parser.parsePrimary()])])
parser.advanceAfterBlockEnd(tag.value)
return node
}
}
module.exports = YieldExtension
@morrelinko
Copy link
Author

morrelinko commented Nov 22, 2017

How to use

Before (using blocks)

<!-- Parent Template -->
<html>
<head>
    <title> 
        {% block title %} 
        {% endblock %}
    </title>
</head>
</html>
<!-- Child template -->

{% block title %}Home Page{% endblock %}

Now (with Yield)

<!-- Parent Template -->
<html>
<head>
    <title> {% yield title '' %} </title>
</head>
</html>
<!-- Child template -->

{% yield title 'Home Page' %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment