Product
Introducing Ruby Support in Socket
Socket is launching Ruby support for all users. Enhance your Rails projects with AI-powered security scans for vulnerabilities and supply chain threats. Now in Beta!
The pug-walk npm package is designed for walking through the abstract syntax tree (AST) of Pug templates. It allows developers to traverse and manipulate nodes in the AST, enabling operations such as modification, filtering, and analysis of Pug templates.
Walking the AST
This example demonstrates how to traverse a Pug template's AST to find all `div` tags and add an `id` attribute to them. The `walk` function takes the AST and a callback function that is applied to every node. If the node matches the criteria (a `div` tag in this case), a new attribute is added.
const pug = require('pug');
const pugWalk = require('pug-walk');
const ast = pug.parser.parse('div(class=classes)');
pugWalk.walk(ast, (node, replace) => {
if (node.type === 'Tag' && node.name === 'div') {
node.attrs.push({
name: 'id',
val: '"dynamic-id"',
mustEscape: false
});
replace(node);
}
});
Filtering Nodes
This code snippet shows how to filter nodes of a specific type, in this case, `Conditional` nodes, from a Pug template's AST. The `walk` function is used to traverse the AST, and nodes that match the specified condition are added to an array for further processing.
const pug = require('pug');
const pugWalk = require('pug-walk');
const ast = pug.parser.parse('div
if condition
p True
else
p False');
const filteredNodes = [];
pugWalk.walk(ast, node => {
if (node.type === 'Conditional') {
filteredNodes.push(node);
}
}, {includeDependencies: true});
htmlparser2 is a fast HTML parser with a similar API to pug-walk but for HTML instead of Pug templates. It provides a robust and forgiving parser and a flexible tree traversal API, but it does not directly support Pug's syntax or AST structure.
cheerio is a fast, flexible, and lean implementation of core jQuery designed specifically for the server. It allows for manipulation and traversal of HTML documents with a familiar jQuery-like syntax. While it offers similar DOM manipulation and traversal capabilities, it operates on HTML rather than Pug's AST.
esprima is a high performance, standard-compliant ECMAScript parser that provides a similar AST traversal and manipulation API for JavaScript code. While it serves a similar purpose in traversing and manipulating ASTs, it is focused on JavaScript rather than Pug templates.
Walk and transform a Pug AST
npm install pug-walk
var walk = require('pug-walk');
walk(ast, before, after, options)
Traverse and optionally transform a Pug AST.
ast
is not cloned, so any changes done to it will be done directly on the AST provided.
before
and after
are functions with the signature (node, replace)
. before
is called when a node is first seen, while after
is called after the children of the node (if any) have already been traversed.
The replace
parameter is a function that can be used to replace the node in the AST. It takes either an object or an array as its only parameter. If an object is specified, the current node is replaced by the parameter in the AST. If an array is specified and the ancestor of the current node allows such an operation, the node is replaced by all of the nodes in the specified array. This way, you can remove and add new nodes adjacent to the current node. Whether the parent node allows array operation is indicated by the property replace.arrayAllowed
, which is set to true when the parent is a Block and when the parent is a Include and the node is an IncludeFilter.
If before
returns false
, the children of this node will not be traversed and left unchanged (unless replace
has been called). Otherwise, the returned value of before
is ignored. The returned value of after
is always ignored. If replace()
is called in before()
with an array, and before()
does not return false
, the nodes in the array are still descended.
options
can contain the following properties:
includeDependencies
(boolean): Walk the AST of a loaded dependent file (i.e., includes and extends). Defaults to false
.parents
(array): Nodes that are ancestors to the current ast
. This option is used mainly internally, and users usually do not have to specify it. Defaults to []
.var lex = require('pug-lexer');
var parse = require('pug-parser');
// Changing content of all Text nodes
// ==================================
var source = '.my-class foo';
var dest = '.my-class bar';
var ast = parse(lex(source));
ast = walk(ast, function before(node, replace) {
if (node.type === 'Text') {
node.val = 'bar';
// Alternatively, you can replace the entire node
// rather than just the text.
// replace({ type: 'Text', val: 'bar', line: node.line });
}
}, {
includeDependencies: true
});
assert.deepEqual(parse(lex(dest)), ast);
// Convert all simple <strong> elements to text
// ============================================
var source = 'p abc #[strong NO]\nstrong on its own line';
var dest = 'p abc #[| NO]\n| on its own line';
var ast = parse(lex(source));
ast = walk(ast, function before(node, replace) {
// Find all <strong> tags
if (node.type === 'Tag' && node.name === 'strong') {
var children = node.block.nodes;
// Make sure that the Tag only has one child -- the text
if (children.length === 1 && children[0].type === 'Text') {
// Replace the Tag with the Text
replace({ type: 'Text', val: children[0].val, line: node.line });
}
}
}, {
includeDependencies: true
});
assert.deepEqual(parse(lex(dest)), ast);
// Flatten blocks
// ==============
var ast = {
type: 'Block',
nodes: [
{ type: 'Text', val: 'a' },
{
type: 'Block',
nodes: [
{ type: 'Text', val: 'b' },
{
type: 'Block',
nodes: [ { type: 'Text', val: 'c' } ]
},
{ type: 'Text', val: 'd' }
]
},
{ type: 'Text', val: 'e' }
]
};
var dest = {
type: 'Block',
nodes: [
{ type: 'Text', val: 'a' },
{ type: 'Text', val: 'b' },
{ type: 'Text', val: 'c' },
{ type: 'Text', val: 'd' },
{ type: 'Text', val: 'e' }
]
};
// We need to use `after` handler instead of `before`
// handler because we want to flatten the innermost
// blocks first before proceeding onto outer blocks.
ast = walk(ast, null, function after(node, replace) {
if (node.type === 'Block' && replace.arrayAllowed) {
// Replace the block with its contents
replace(node.nodes);
}
});
assert.deepEqual(dest, ast);
MIT
FAQs
Walk and transform a pug AST
The npm package pug-walk receives a total of 1,203,099 weekly downloads. As such, pug-walk popularity was classified as popular.
We found that pug-walk demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket is launching Ruby support for all users. Enhance your Rails projects with AI-powered security scans for vulnerabilities and supply chain threats. Now in Beta!
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.