eslint-plugin-ejs-templates
v0.6.1
Published
ESLint plugin for EJS (Embedded JavaScript) templates — processor and rules
Maintainers
Readme
eslint-plugin-ejs-templates
An ESLint plugin for EJS (Embedded JavaScript) templates.
EJS files are parsed by ejs-template-parser, with tree-sitter-embedded-template via web-tree-sitter, which provides accurate position information for all lint messages and autofixes.
Features
- EJS processor – extracts each EJS tag into its own virtual JS block so standard ESLint rules can inspect the embedded JavaScript
- Autofix support – most rules support autofix; run
eslint --fixto apply fixes (no-comment-across-tags,no-complex-statements,no-function-blockandno-global-function-callhave no autofix;no-stray-close-delimiterhas suggestions) - Autofix for built-in
no-negated-condition– supplies the fix ESLint itself cannot produce for EJSif/elsetag pairs ejs-templates/no-comment-across-tags– flags a block comment opened in a tag and closed in a later one, which comments out the template in betweenejs-templates/no-comment-empty-line– flags comment tags that leave an empty line (missing-%>close)ejs-templates/no-complex-statements– disallows complex statements (try, while, switch, etc.) in templates to keep them simpleejs-templates/no-function-block– disallows function/arrow statement blocks in templates to keep logic simpleejs-templates/no-global-function-call– disallows direct function calls in EJS tags (withinclude()allowed by default)ejs-templates/no-multiline-output– flags (and auto-fixes) output tags whose conditional renders multiple linesejs-templates/no-stray-close-delimiter– flags a close delimiter (%>,-%>,_%>) in the text, which EJS drops, with suggestions to write it literally or delete itejs-templates/no-one-sided-trim– a tag trims on both sides of it or on none:<%_with_%>or-%>,<%and output tags with%>ejs-templates/output-semi– enforces semicolon style for output tags (<%= %>,<%- %>) (default:never)ejs-templates/prefer-encoded– flags<%- … %>and suggests<%= … %>(always, default), or flags<%= … %>and suggests<%- … %>(never)ejs-templates/prefer-output– suggests (and auto-fixes) simple if-wrappers into output ternariesejs-templates/prefer-single-line-tags– collapses multiline EJS tags to single-line tagsejs-templates/prefer-slurping-codeonly– flags<% … %>code tags that can be safely converted to<%_ … _%>ejs-templates/prefer-slurp-multiline– flags<% … %>code tags spanning lines, written<%_ … _%>ejs-templates/format– normalizes spacing inside tags and multiline closing delimiter layoutejs-templates/indent-tag– enforces brace-depth–based indentation on standalone<%_ … _%>tagsejs-templates/indent-content– indents the lines of a<%_ … _%>tag spanning lines with the tagejs-templates/slurp-newline– ensures<%_ … _%>tags are on their own line
Installation
npm install --save-dev eslint eslint-plugin-ejs-templatesUsage
Add the plugin to your ESLint flat config (eslint.config.js):
import { defineConfig } from 'eslint/config';
import templates from 'eslint-plugin-ejs-templates';
import eslint from '@eslint/js';
export default defineConfig([
// Standard JS rules:
eslint.configs.recommended,
// Apply the EJS processor to all *.ejs files with no rules (opt-in below):
...templates.configs.base,
{
files: ['**/*.ejs'],
rules: {
// No specific ordering requirement:
'ejs-templates/no-comment-across-tags': 'error',
'ejs-templates/no-comment-empty-line': 'error',
'ejs-templates/no-complex-statements': 'error',
'ejs-templates/no-function-block': 'error',
'ejs-templates/no-global-function-call': 'error',
'ejs-templates/no-multiline-output': 'error',
'ejs-templates/no-stray-close-delimiter': 'error',
'ejs-templates/no-one-sided-trim': 'error',
'ejs-templates/output-semi': ['error', 'never'],
'ejs-templates/prefer-output': 'error',
'ejs-templates/prefer-encoded': 'error', // 'always' (default) or 'never'
// Apply remaining rules in this order:
'ejs-templates/prefer-slurp-multiline': 'error',
'ejs-templates/prefer-slurping-codeonly': 'error',
'ejs-templates/prefer-single-line-tags': 'error',
'ejs-templates/slurp-newline': 'error',
'ejs-templates/indent-tag': 'error',
'ejs-templates/indent-content': 'error',
'ejs-templates/format': 'error',
},
},
]);Or use the customize helper to enable all rules with a single call and convenient options:
import { defineConfig } from 'eslint/config';
import ejs from 'eslint-plugin-ejs-templates';
export default defineConfig([
...ejs.configs.customize({
// allowedGlobals: ['include'], // extra global functions to allow (default: [])
// experimental: true, // enable experimental rules: none at the moment (default: false)
// html: 'extension', // 'always' | 'never' | 'extension' (default)
// stylisticBlocklist: false, // disable conflicting @stylistic rules (default: false)
// prettierBlocklist: false, // disable prettier/prettier rule (default: false)
}),
]);customize also accepts additional ESLint Config entries (spread after the options object)
that will be scoped to **/*.ejs files:
export default defineConfig([
...ejs.configs.customize(
{ allowedGlobals: ['include'] },
{ rules: { 'no-var': 'error' } },
js.configs.recommended,
stylistic.configs.customize({
jsx: false,
semi: true, // This plugin is optimized for 'semi: true' configuration.
}),
),
]);Options
| Option | Type | Default | Description |
| -------------------- | ------------------------------------ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| allowedGlobals | string[] | [] | Extra global function names that no-global-function-call will not flag |
| experimental | boolean | false | Turns on the experimental rules: none at the moment |
| html | 'always' \| 'never' \| 'extension' | 'extension' | Controls the prefer-encoded option: always for all .ejs files, never for all .ejs files, or always for *.html.ejs and never for the rest |
| stylisticBlocklist | boolean | false | Turns off @stylistic rules that conflict with EJS formatting (eol-last, brace-style and multiline-ternary) |
| prettierBlocklist | boolean | false | Turns off the prettier/prettier rule when Prettier is also configured |
customize() turns on every rule of the plugin with error but prefer-encoded (by html). It
leaves alone an ejs-templates rule the configurations it is given set, and reads the rules of
@stylistic they turn on:
@stylistic/indentindents the lines of the code of tags:indent-content, which indents the same lines, is off.indent-tagplaces the tags, and the messages of@stylistic/indenton the first line of a tag are dropped.@stylistic/indent-binary-opsasks for some lines of right operands as much indentation as the line their expression starts on:indent-contentaccepts it (binaryOperands: 'greaterOrEqual').
A configuration with the recommended JavaScript rules and @stylistic, its conflicting rules off:
export default defineConfig([
...ejs.configs.customize(
{ html: 'never', stylisticBlocklist: true, prettierBlocklist: true },
js.configs.recommended,
stylistic.configs.customize({ jsx: false, semi: true }),
),
]);Then run ESLint as usual:
npx eslint "**/*.ejs"
# or auto-fix violations:
npx eslint --fix "**/*.ejs"Note on incompatible rules
The EJS processor lints each tag as a separate virtual JavaScript block.
no-undefdiagnostics are suppressed internally for*.ejsvirtual blocks, so you do not need to disableno-undefin your ESLint config.
Note on the code the processor adds
The virtual JavaScript has code the template does not: a marker comment before the code of each tag, a
;after the expression of an output tag, and a function and a block around them all. The messages of other rules on that code are dropped. Every line of the code of a tag is at its column in the template, so that rules measuring indentation measure it as there.
Note on ESLint directives in EJS comments
You can use supported ESLint directive comments inside EJS comments:
<%# eslint-disable no-var %><%# eslint-enable no-var %><%# eslint-disable-next-line no-var %>Example:
<%# eslint-disable-next-line no-var %> <% var value = 1; %>Regular EJS comments that are not ESLint directives continue to be ignored.
Rules
The following rules have no specific ordering requirement (they can appear in any position):
no-comment-across-tagsno-comment-empty-lineno-complex-statementsno-function-blockno-global-function-callno-multiline-outputno-stray-close-delimiterno-one-sided-trimoutput-semi
Apply prefer-output before prefer-encoded.
The built-in customize() config already does this by enabling prefer-output
in the base EJS rules and applying prefer-encoded in later config entries.
Apply the remaining rules in the following order for best results:
prefer-slurp-multiline— convert multiline<% %>to<%_ %>firstprefer-slurping-codeonly— convert single-line<% %>to<%_ %>prefer-single-line-tags— collapse remaining multiline tagsslurp-newline— ensure slurp tags are on their own lineindent-tag— enforce brace-depth indentationindent-content— indent the lines of a tag spanning lines with itformat— apply final whitespace/layout normalization
ejs-templates/prefer-slurp-multiline
Prefers <%_ … _%> (whitespace-slurping) over <% … %> for code tags spanning lines, as
prefer-slurping-codeonly does for the ones on one line.
A code tag opening with <% and spanning lines, closed by %> or -%>, is reported, whether its
code opens or closes blocks or not. The fix writes it <%_ … _%>, its code trimmed: the first line
of the code joins the opening delimiter, and the closing one follows the last line. Output tags
(<%=, <%-), comments and tags already opening with <%_ are not reported.
The fix changes the blanks and the line breaks EJS renders, which slurp tags are for: <%_ slurps
the blanks before the tag on its line, _%> the blanks after it and the line break that follows.
On a tag inside text, the blanks of the text next to the tag are slurped too, which
slurp-newline then puts on a line of its own.
Apply it before prefer-single-line-tags, which
splits the slurp tag it writes into tags of one line each, joined by their slurp delimiters.
| | |
| ----------- | ----------------------------------------------------------------- |
| Fixable | Yes — eslint --fix writes the tag <%_ … _%>, its code trimmed |
<!-- ✗ violation -->
<%
if (condition) {
%>
x
<% } %>
<!-- ✓ fixed -->
<%_ if (condition) { _%>
x
<% } %>A tag of several statements keeps its lines:
<!-- ✗ violation -->
<%
const a = 1;
const b = 2;
%>
<!-- ✓ fixed -->
<%_ const a = 1;
const b = 2; _%>ejs-templates/format
Applies final formatting normalization to EJS tags:
- ensures a single space around trimmed content (
<% foo %>) - controls multiline closing delimiter style
| | |
| ----------- | ----------------------------------------------------- |
| Fixable | Yes — eslint --fix normalizes tag whitespace/layout |
Options:
{ multilineClose: 'new-line' }(default) — for originally multiline tags, move close delimiter to a new line aligned with opening tag indentation{ multilineClose: 'same-line' }— keep close delimiter on the same line as content after formatting
// eslint.config.js
{
files: ['**/*.ejs'],
rules: {
'ejs-templates/format': ['error', { multilineClose: 'new-line' }],
},
}<!-- input -->
<%_
doWork(); _%>
<!-- with multilineClose: 'new-line' (default) -->
<%_ doWork();
_%>
<!-- with multilineClose: 'same-line' -->
<%_ doWork(); _%>ejs-templates/indent-content
Indents the lines of a standalone <%_ … _%> tag spanning lines with the tag, each at the depth of
its own blocks, wherever the tag is: indent-tag places the tag.
| | |
| ----------- | -------------------------------------------------- |
| Fixable | Yes — eslint --fix re-indents the lines of a tag |
<!-- ✗ violation: the lines not indented with the tag -->
<%_ items.forEach((item) => {
show(item);
});
_%>
<!-- ✓ fixed -->
<%_ items.forEach((item) => {
show(item);
});
_%>Options:
binaryOperands(default'greater') — the line where the right operand of a binary expression starts, apart from its left one, is accepted indented more than the line the expression starts on, by any amount, or as much with'greaterOrEqual', as@stylistic/indent-binary-opsasks for some lines; one level more otherwise.customize()sets'greaterOrEqual'when the configurations it is given turn that rule on.
@stylistic/indent indents the same lines, those after the first one of a tag: customize() turns
indent-content off when the configurations it is given turn @stylistic/indent on. Its messages
on the first line of a tag, which indent-tag places, are dropped.
ejs-templates/indent-tag
Enforces brace-depth–based indentation (two spaces per level) on standalone
<%_ … _%> tags. The lines of a tag spanning lines move with its first line as written, which
indent-content indents with the tag.
Consistent indentation improves readability of nested template logic.
| | |
| ----------- | --------------------------------------------------- |
| Fixable | Yes — eslint --fix adjusts the leading whitespace |
<!-- ✗ violation: wrong indentation -->
<%_ if (show) { _%>
<%_ doWork(); _%>
<%_ } _%>
<!-- ✓ fixed -->
<%_ if (show) { _%>
<%_ doWork(); _%>
<%_ } _%>ejs-templates/no-comment-across-tags
Disallows a block comment opened in an EJS tag and closed in a later one. EJS compiles the template to one function, so the comment also comments out the template in between — its text and its other tags — and the blocks around it no longer read as written.
| | | | ----------- | --- | | Fixable | No |
<!-- ✗ violation: the comment hides the text and the closing tag -->
<%_ /* if (enabled) { _%>
enabled
<%_ } */ _%>
<!-- ✓ allowed: a comment within one tag -->
<%_ /* if (enabled) { */ _%>There is no fix: only the author knows what the comment was meant to hide. The message is at the
tag opening the comment. The tags in between are part of the comment, as EJS compiles them: the
blocks their code would open and close are none, so ejs-templates/indent-tag expects them at the
depth of the comment.
The rule reports the comment-across-tags diagnostics of
ejs-template-parser, which are in the coordinates of the
template rather than of the virtual JavaScript: the processor reports them for the rule. A block
directive comment anywhere in the template turns it off for that template,
<%# eslint-disable ejs-templates/no-comment-across-tags %>, without an eslint-enable after it;
eslint-disable-next-line and a range closed by eslint-enable cannot.
ejs-templates/no-comment-empty-line
Requires standalone EJS comment tags to use -%> (trim-newline close) to avoid
leaving an empty line in the rendered output. A <%# comment %> tag that is on
its own line emits a blank line; <%# comment -%> suppresses it.
| | |
| ----------- | ------------------------------------------ |
| Fixable | Yes — eslint --fix changes %> to -%> |
<!-- ✗ violation: leaves an empty line in output -->
<%# This is a comment %>
<!-- ✓ fixed: no empty line in output -->
<%# This is a comment -%>ejs-templates/no-complex-statements
Disallows complex statements in EJS tags that increase logic complexity and reduce maintainability. By default, forbidden statement types include:
TryStatement(try/catch)WhileStatement,DoWhileStatement(while/do-while loops)SwitchStatement(switch)FunctionDeclaration(function declarations)ClassDeclaration(class declarations)LabeledStatement(labeled blocks)DebuggerStatement(debugger)WithStatement(with statements)
These statements encourage moving logic outside of templates. Use simpler
constructs like if/else, for/for-of loops, and array methods instead.
| | | | ----------- | --- | | Fixable | No |
<!-- ✗ violation: try/catch statements -->
<% try {
const result = JSON.parse(data);
} catch (e) {
console.error(e);
} %>
<!-- ✓ better: handle errors in the controller, pass clean data to template -->
<% const result = data; %>
<!-- ✗ violation: while loop -->
<% let i = 0;
while (i < items.length) {
console.log(items[i]);
i++;
} %>
<!-- ✓ better: use for-of -->
<% for (const item of items) {
console.log(item);
} %>
<!-- ✗ violation: switch statement -->
<% switch (statusCode) {
case 200:
message = 'OK';
break;
case 404:
message = 'Not Found';
break;
} %>
<!-- ✓ better: use simple conditional or pass logic from controller -->
<% const message = statusCode === 200 ? 'OK' : statusCode === 404 ? 'Not Found' : 'Unknown'; %>Options:
{ disallow: ['TryStatement', 'SwitchStatement'] }— customize which statement types are forbidden- Each item can be a string (statement type) or an object
{ type: 'StatementType', message: 'Custom message' }
// eslint.config.js
{
files: ['**/*.ejs'],
rules: {
'ejs-templates/no-complex-statements': [
'error',
{
disallow: [
'TryStatement',
'SwitchStatement',
{ type: 'WhileStatement', message: 'Use for-of loops instead of while loops' },
{ type: 'FunctionDeclaration', message: 'Declare functions outside templates' },
],
},
],
},
}ejs-templates/no-function-block
Disallows function bodies that use statement_block ({ ... }) in templates,
including:
- function declarations
- function expressions
- arrow functions with block bodies
Reason: statement_block inside templates increases logic complexity and
reduces readability/maintainability.
| | | | ----------- | --- | | Fixable | No |
<!-- ✗ violation: arrow function with block body -->
<% foos.filter(foo => { return foo.ok; }); %>
<!-- ✓ allowed: concise arrow expression -->
<% foos.filter(foo => foo.ok); %>
<!-- ✓ allowed: concise arrow expression -->
<% foos.map(foo => foo.name); %>Alternatives when logic grows:
- Prefer concise arrow expressions (
foo => foo.ok) when possible. - Pass the function through template data/context and call it as a method.
- Prefer
for...ofloops overforEachcallback blocks for control flow. - Split complex template parts into partials and use
include.
ejs-templates/no-global-function-call
Disallows direct function calls in EJS tags (foo()), while allowing
include() by default. Method calls (obj.foo()) are ignored.
If a function is passed through the template context, call it as a method such
as locals.method(). This rule allows that form because it only blocks direct
calls like method().
| | |
| ----------- | ------------------------------------------- |
| Fixable | No |
| Default | include is allowed (allow: ['include']) |
<!-- ✗ violation -->
<% doWork(); %>
<!-- ✓ allowed by default -->
<% include('partial.ejs'); %>
<!-- ✓ not checked by this rule (method call) -->
<% locals.save(); %>Options:
{ allow: ['name1', 'name2'] }— adds direct function names to the allowlist;customize()sets it fromallowedGlobals
// eslint.config.js
{
files: ['**/*.ejs'],
rules: {
'ejs-templates/no-global-function-call': ['error', { allow: ['include'] }],
},
}Security implications:
- Allowing dangerous direct calls (for example
exec()) inside templates can lead to command execution risks if arguments are user-controlled. - Prefer keeping the allowlist minimal and avoid granting process-execution primitives to template code.
- If your project must allow such calls, validate/sanitize all inputs and isolate execution contexts.
Autofix for the built-in no-negated-condition rule
ESLint's own no-negated-condition rule already reports negated if/else
conditions inside EJS templates: the virtual JavaScript this plugin builds keeps
the if/else structure intact, so the rule sees it and reports it at the right
position. What ESLint cannot do is fix it — the branch bodies are template markup
living between tags, outside the JavaScript the rule has access to.
This plugin supplies that missing fix. There is no ejs-templates rule to enable:
turn on the built-in rule and eslint --fix will apply the swap.
// eslint.config.js
{
files: ['**/*.ejs'],
rules: {
'no-negated-condition': 'error',
},
}<!-- ✗ violation -->
<% if (!user.active) { %>
<span>Inactive</span>
<% } else { %>
<span>Active</span>
<% } %>
<!-- ✓ fixed -->
<% if (user.active) { %>
<span>Active</span>
<% } else { %>
<span>Inactive</span>
<% } %>Negated tests are recognised as !cond, !(a && b), a !== b and a != b; the
comparison operators are inverted (!== becomes ===) rather than wrapped in a
further negation. Branch bodies are moved verbatim, so markup and indentation are
preserved, and bodies may contain any number of nested tags. Each body moves with
the delimiters next to it, which slurp its blanks and drop its line breaks: the
close delimiter of the tag before it (-%>, _%>) and the open delimiter of the
tag after it (<%_). Each branch renders what it rendered.
The same fix covers the ternary form the built-in rule reports, inside an output tag:
<!-- ✗ violation -->
<%= !cond ? a : b %>
<%= a !== b ? x : y %>
<!-- ✓ fixed -->
<%= cond ? b : a %>
<%= a === b ? y : x %>Nothing is fixed where the built-in rule does not report: an if without an
else (there is no branch to swap with), or an else if chain (swapping would
not preserve the chain). A ternary in a code tag is reported but not fixed, since
it produces no output to swap.
ejs-templates/no-multiline-output
Flags output tags whose conditional renders multiple lines, and auto-fixes them into a conditional block. Escaping markup into a string hides the template's structure: the output cannot be seen, indented, or edited as markup.
<!-- ✗ violation -->
<%- condition ? 'first\nsecond' : '' %>
<!-- ✓ fixed -->
<% if (condition) { %>first
second<% } %>The branch text is written flush against plain <% %> tags. Slurp tags would
swallow the whitespace and newlines around them, so the block would render
differently from the output tag it replaced; plain tags emit nothing themselves
and consume nothing around them, so the rendered output is unchanged — including
for an indented or inline tag, whose surrounding text is preserved exactly. The
last tag closes with the delimiter of the output tag: after a -%> or a _%>,
the line break (and the blanks a _%> slurps) stays dropped.
A non-empty alternate branch becomes an else:
<!-- ✗ violation -->
<%- condition ? 'aaa\nbbb' : 'ccc\nddd' %>
<!-- ✓ fixed -->
<% if (condition) { %>aaa
bbb<% } else { %>ccc
ddd<% } %>This is the counterpart to prefer-output, which
collapses the opposite case. The two never apply to the same tag: prefer-output
only produces single-line ternaries, and this rule only reports multiline ones.
Only ternaries whose branches are plain string literals are reported — a template literal can interpolate, so its rendered text is not known statically.
One case is reported but deliberately not fixed: a <%= tag whose text
contains &, <, >, " or '. <%= escapes its value, while the template
text the fix produces is emitted raw, so no rewrite preserves the output. A <%-
tag has no such limit.
This rule is enabled by default by customize(). To turn it off, set it in a
config entry of your own — customize() leaves any ejs-templates rule you
configure yourself untouched:
// eslint.config.js
{
files: ['**/*.ejs'],
rules: {
'ejs-templates/no-multiline-output': 'off',
},
}ejs-templates/no-stray-close-delimiter
Disallows a close delimiter (%>, -%>, _%>) in the text of a template, outside of any tag.
EJS drops it from the output, along with the line break after a -%> or a _%> and the blanks
after a _%>. It is usually a typo, a delimiter left behind by an edit; %%> writes a literal
%>. Whatever is before it: text alone, or a code tag, an output tag or none.
| | | | --------------- | -------------------------------- | | Fixable | No | | Suggestions | Write it literally, or delete it |
<!-- ✗ violation: in text alone, EJS renders `plain text more` -->
plain text %> more
<!-- ✗ violation: after an output tag, EJS drops the %> -->
CREATE INDEX ON `<%= bucket %>` %>(tokenDate);
<!-- ✓ suggestion: write it literally, the output then has it -->
CREATE INDEX ON `<%= bucket %>` %%>(tokenDate);
<!-- ✓ suggestion: delete it, the output unchanged -->
CREATE INDEX ON `<%= bucket %>` (tokenDate);The two suggestions, written with editTemplate() of ejs-template-parser, the rest of the template
rendering as before:
- Write it literally:
%>becomes%%>,-%>-%%>and_%>_%%>; the output then has the delimiter, and what EJS dropped along with it. - Delete it, the output unchanged: with what EJS removes along with it, the line break right
after a
-%>or a_%>, and the blanks after a_%>. Blanks before it that a<%_after would then slurp are kept, written as<%- ' ' %>.
There is no fix: a stray delimiter is as often a typo to delete as a literal to escape.
The rule reports the stray-close-delimiter diagnostics of
ejs-template-parser, which are in the text of the template,
outside of the virtual JavaScript: the processor reports them for the rule. A block directive
comment anywhere in the template turns it off for that template,
<%# eslint-disable ejs-templates/no-stray-close-delimiter %>, without an eslint-enable after
it; eslint-disable-next-line and a range closed by eslint-enable cannot.
ejs-templates/no-one-sided-trim
A tag trims on both sides of it or on none. <%_ slurps the blanks before a tag on its line;
-%> drops the line break after it, _%> the blanks after it and the line break. A tag trimming
one side alone is reported:
| Tag | Fix |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| An output tag (<%=, <%-) closed by -%>, _%> | %>, what the close removed removed from the text, the output unchanged |
| A code tag opened by <%, closed by -%>, _%> | opened by <%_ at the start of its line; reported alone when blanks or text are before it |
| A code tag opened by <%_, closed by %> | _%> and a blank line before the end of its line, -%> before text: the output unchanged |
An output tag cannot open with <%_. Two are left alone: one whose code has an include(…), the
output of a partial ending with a line break, which a -%> keeps from doubling the line break of
the template; and one ending the template, nothing after it but its final line break, which a
-%> keeps out of the output of the template, a partial. Comment tags are left alone: a comment on
a line of its own closes with -%> (no-comment-empty-line).
| | |
| ----------- | -------------------------------------------------- |
| Fixable | Yes — eslint --fix makes the tag trim both sides |
<!-- ✗ violation: the -%> removes nothing -->
<%- attributes -%>/>
<!-- ✓ fixed -->
<%- attributes %>/>
<!-- ✗ violation: the -%> removes the line break -->
<%= name -%>
text
<!-- ✓ fixed, the line joined, the output unchanged -->
<%= name %>text
<!-- ✗ violation: trims what is after it alone -->
<% if (show) { -%>
<!-- ✓ fixed -->
<%_ if (show) { -%>
<!-- ✗ violation: renders an empty line, which the closing delimiter does not tell -->
<%_ } %>
<!-- ✓ fixed: the empty line written out -->
<%_ } _%>
<!-- ✓ allowed -->
<%- include('partial') -%>Every fix keeps the output. A <%_ … %> before the end of its line gets a line break after its
_%>, which slurps it, the empty line the tag rendered written out. A <% … -%> is opened by <%_
at the start of its line alone, where <%_ slurps nothing: indented or with text before it, <%_
would slurp the blanks it renders, and the tag is reported without a fix. Before a <%%, which
writes without clearing what the next text loses, an output tag is reported without a fix.
ejs-templates/output-semi
Enforces semicolon style at the end of the content of output tags, <%= ... %> and <%- ... %>,
on one line or spanning lines.
This rule is independent from the ordered formatting pipeline
(prefer-slurp-multiline → format) and does not affect the
behavior of the other plugin rules.
| | |
| ----------- | ---------------------------------------------------- |
| Fixable | Yes — eslint --fix adds/removes trailing semicolon |
| Default | never |
Options:
'never'(default) — disallow trailing semicolon'always'— require trailing semicolon
// eslint.config.js
{
files: ['**/*.ejs'],
rules: {
'ejs-templates/output-semi': ['error', 'never'],
},
}<!-- with 'never' (default) -->
<%= value; %>
<!-- fixed -->
<%= value %>
<!-- with 'always' -->
<%= value %>
<!-- fixed -->
<%= value; %>ejs-templates/prefer-encoded
Enforces a consistent output-tag style across the template.
'always'(default): prefer<%=(HTML-encoded) over<%-(raw). Flags every<%- … %>tag. Use this when templates render HTML and you want XSS-safe defaults.'never': prefer<%-(raw / unescaped) over<%=(HTML-encoded). Flags every<%= … %>tag. Use this when output is already trusted or escaped by other means.
| | |
| ----------- | ------------------------------------------------------------------------- |
| Fixable | Yes — eslint --fix converts between <%- and <%= based on the option |
// eslint.config.js
{
files: ['**/*.ejs'],
rules: {
// 'always' (default) — prefer HTML-encoded output:
'ejs-templates/prefer-encoded': 'error',
// 'never' — prefer raw output:
'ejs-templates/prefer-encoded': ['error', 'never'],
},
}<!-- with 'always' (default) -->
<%- value %>
<!-- fixed -->
<%= value %>
<!-- with 'never' -->
<%= value %>
<!-- fixed -->
<%- value %>ejs-templates/prefer-output
Suggests replacing simple output-wrapper conditionals with a ternary output tag. The rule applies only when the full wrapper (opening tag, content, and closing/else tags) is on a single line.
Primary target pattern:
<% if (condition) { %>content<% } %><% if (condition) { %>A<% } else { %>B<% } %>
Auto-fixed form:
<%= condition ? 'content' : '' %><%= condition ? 'A' : 'B' %>
The strings are what EJS renders of the branches, so the output is unchanged: <%% and %%> become
<% and %> (written <\x25 and %\x3E in the string, which would otherwise open or close a tag),
and comment tags inside a branch render nothing. When a branch has a character <%= would escape
(&, <, >, ', "), the fix writes a raw output tag, <%- … %>, since the text of a branch is
not escaped. The close delimiter of the last tag (-%>, _%>) is kept.
| | |
| ----------- | ------------------------------------------------------------- |
| Fixable | Yes — eslint --fix for simple single-line wrapper patterns |
| Notes | Conservative fix: skips nested EJS content inside the wrapper |
<!-- ✗ violation -->
<% if (showTitle) { %>Title<% } %>
<!-- ✓ fixed -->
<%= showTitle ? 'Title' : '' %>
<!-- ✗ violation (if/else wrapper) -->
<% if (showTitle) { %>Title<% } else { %>Untitled<% } %>
<!-- ✓ fixed -->
<%= showTitle ? 'Title' : 'Untitled' %><!-- still reported, but not auto-fixed (inline empty if) -->
<% if (showTitle) { } %>
<!-- not applied (multiline wrapper) -->
<% if (showTitle) { %>
Title
<% } %>ejs-templates/prefer-single-line-tags
Flags multiline tags when either:
- their content has structural braces, or
- their content becomes a single line after trimming.
It also flags a single-line tag that closes more than one block, such as
<%_ } } _%>:
<!-- ✗ violation -->
<%_ } } _%>
<!-- ✓ fixed -->
<%_ } _%>
<%_ } _%>A tag closing two blocks at once cannot sit at a single indent depth, so
indent-tag has no correct answer for it and a reader has to
count braces to follow the nesting. A tag that closes one block and opens another
(<%_ } else { _%>) is an ordinary continuation and is left alone.
For structural-brace cases, autofix keeps brace boundaries ({ and }) as
separate tags and keeps the content between them in a single tag.
A tag on its own line becomes one tag per line, and the generated tags close with
_%> and open with <%_ so the line break between them is slurped away.
An inline tag — one with template text either side of it — instead becomes
adjacent tags on the same line. The opening delimiter the author wrote stays on
the first tag only, since repeating <%_ would ask for the whitespace before the
tag to be slurped once per generated tag; later tags open with whatever pairs with
the closing delimiter:
<% } } %> becomes <% } %><% } %>
<% } } _%> becomes <% } _%><%_ } _%>
<%_ } } %> becomes <%_ } %><% } %>
<%_ } } _%> becomes <%_ } _%><%_ } _%>Either way the rendered output is unchanged.
Keeping tags single-line avoids visual confusion between template output text and EJS control flow, making template intent easier to scan.
| | |
| ----------- | -------------------------------------- |
| Fixable | Yes — eslint --fix collapses the tag |
<!-- ✗ violation: single phrase split across lines -->
<%_
if (generateSpringAuditor) {
_%>
<!-- ✓ fixed -->
<%_ if (generateSpringAuditor) { _%><!-- ✗ violation: multiline content that trims to one line -->
<%_
code;
_%>
<!-- ✓ fixed -->
<%_ code; _%><!-- ✗ violation: block with body and close -->
<%_
if (x) {
doWork();
}
_%>
<!-- ✓ fixed: one tag per boundary -->
<%_ if (x) { _%>
<%_ doWork(); _%>
<%_ } _%>ejs-templates/prefer-slurping-codeonly
Prefers <%_ … _%> (whitespace-slurping) over <% … %> for single-line code
tags that are logic-only (no direct output), whose content has balanced braces,
and does not open or close a brace block.
Use this for code-only control logic; blocks that generate output should keep their output-specific delimiters.
| | |
| ----------- | ------------------------------------------------------ |
| Fixable | Yes — eslint --fix converts <% … %> to <%_ … _%> |
<!-- ✗ violation -->
<% const cssClass = active ? 'active' : ''; %>
<!-- ✓ fixed -->
<%_ const cssClass = active ? 'active' : ''; _%>Tags that open or close brace depth are left unchanged:
<% if (condition) { %> ← not flagged (opens a block)
<% } %> ← not flagged (closes a block)ejs-templates/slurp-newline
Ensures <%_ … _%> whitespace-slurping tags are on their own line. <%_ slurps the blanks before
it on its line, _%> the blanks after it and the line break that follows: on a line of its own, the
tag slurps its indentation and its line, which renders nothing; inline, it slurps the blanks of the
text around it, joining the text before and after it (some text <%_ x _%> more renders
some textmore). Apply this rule after prefer-slurping-* and before indent-tag.
Placing each slurp tag on its own line (then indenting it) makes what it slurps the indentation and the line of the tag alone, and the template easier to read and reason about.
| | |
| ----------- | ----------------------------------------------------- |
| Fixable | Yes — eslint --fix inserts a newline before the tag |
<!-- ✗ violation: slurp tag is inline after other content -->
some text<%_ doWork(); _%>
<!-- ✓ fixed -->
some text
<%_ doWork(); _%>Removed and renamed rules
ejs-templates/experimental-prefer-slurp-multiline
No longer experimental: prefer-slurp-multiline, which
customize() turns on without the experimental option.
ejs-templates/indent
Split into indent-tag, which places a tag at its depth of blocks, and
indent-content, which indents the lines of a tag spanning lines
with it. Its normalizeContent option is indent-content, turned on or off.
ejs-templates/no-output-negated-condition
Removed, along with its later name ejs-templates/no-output-negated-ternary.
Negated output ternaries are reported by ESLint's built-in no-negated-condition
rule, and this plugin supplies the autofix — see
Autofix for the built-in no-negated-condition rule.
Replace either rule name with the built-in one:
// eslint.config.js
{
files: ['**/*.ejs'],
rules: {
'no-negated-condition': 'error',
},
}Supported EJS Delimiters
| Delimiter | Meaning |
| --------- | -------------------------------------- |
| <% | Code (no output) |
| <%= | Output (HTML-escaped) |
| <%- | Output (raw / unescaped) |
| <%_ | Code, trims preceding whitespace |
| <%# | Comment (no output) |
| <%% | A literal <% in the text |
| %%> | A literal %> in the text |
| %> | Standard closing delimiter |
| -%> | Closing delimiter, trims trailing \n |
| _%> | Closing delimiter, trims whitespace |
