Home

Awesome

eslint-plugin-lodash-template

ESLint plugin for John Resig-style micro templating.

npm license npm version npm downloads npm downloads npm downloads npm downloads npm downloads Build Status Coverage Status

It can be used in projects using Underscore.js and Lodash's template.

This plugin supports code checking for templates like the examples below.

<div id="<%= id %>" class="<%= (i % 2 == 1 ? ' even': '') %>">
  <div class="grid_1 alpha right">
    <img class="righted" src="<%= profile_image_url %>"/>
  </div>
  <div class="grid_6 omega contents">
    <p><b><a href="/<%= from_user %>"><%= from_user %></a>:</b> <%= text %></p>
  </div>
</div>
<% for ( var i = 0; i < users.length; i++ ) { %>
  <li><a href="<%= users[i].url %>"><%= users[i].name %></a></li>
<% } %>

Playground on the Web

output sample(on SublimeText):

sample-sublime-text

Features

Installation

npm install --save-dev eslint eslint-plugin-lodash-template

Documentation

See documents.

Usage

Create .eslintrc.* file to configure rules. See also: http://eslint.org/docs/user-guide/configuring.

Example eslint.config.js:

import lodashTemplate from 'eslint-plugin-lodash-template'
export default [
    {
        files: ['**/*.html'],
        ...lodashTemplate.configs['flat/recommended-with-html']
    }
]

Example .eslintrc.js:

module.exports = {
  extends: [
    // add more generic rulesets here, such as:
    // 'eslint:recommended',
    'plugin:lodash-template/recommended-with-html'
  ],
  rules: {
    // override/add rules settings here, such as:
    // 'lodash-template/no-warning-html-comments': 'error'
  }
}

Attention

This plugin does special handling for the following rule warnings in the template.

Rule IDProcess DescriptionAnother way this plugin supports
indentDisable warningslodash-template/scriptlet-indent rule,<br>lodash-template/html-indentrule
@stylistic/indentDisable warningslodash-template/scriptlet-indent rule,<br>lodash-template/html-indent rule
strictDisable warnings--
no-emptyDisable warnings--
max-statements-per-lineDisable warnings--
@stylistic/max-statements-per-lineDisable warnings--
padded-blocksDisable warnings--
@stylistic/padded-blocksDisable warnings--
no-implicit-globalsDisable warnings--
no-multi-spacesDisable warningslodash-template/no-multi-spaces-in-scriptlet rule,<br>lodash-template/no-multi-spaces-in-html-tag rule
@stylistic/no-multi-spacesDisable warningslodash-template/no-multi-spaces-in-scriptlet rule,<br>lodash-template/no-multi-spaces-in-html-tag rule
no-unused-expressionsDisable warnings within interpolate(<%=...%>)--
quotesDisable warnings if doublequote is set--
@stylistic/quotesDisable warnings if doublequote is set--
no-irregular-whitespaceDisable warnings outside template tagslodash-template/no-irregular-whitespace rule

Configs

For eslint.config.js

This plugin provides 7 predefined configs:

For .eslintrc.*

This plugin provides 6 predefined configs:

Rules

The --fix option on the command line automatically fixes problems reported by rules which have a wrench :wrench: below.

<!--RULES_TABLE_START-->

Base Rules (Enabling Correct ESLint Parsing)

Enable this plugin using with:

{
  "extends": "plugin:lodash-template/base"
}
Rule IDDescription
lodash-template/no-script-parsing-errordisallow parsing errors in template

Best Practices (Improve Development Experience)

Enforce all the rules in this category with:

{
  "extends": "plugin:lodash-template/best-practices"
}
Rule IDDescription
lodash-template/no-empty-template-tagdisallow empty micro-template tag. (ex. :ng: <% %>)
lodash-template/no-invalid-template-interpolationdisallow other than expression in micro-template interpolation. (ex. :ng: <%= if (test) { %>)
:wrench:lodash-template/no-semi-in-template-interpolationdisallow the semicolon at the end of expression in micro template interpolation.(ex. :ok: <%= text %> :ng: <%= text; %>)

Recommended (Improve Readability)

Enforce all the rules in this category and all the rules in Best Practices categories with:

{
  "extends": "plugin:lodash-template/recommended"
}
Rule IDDescription
:wrench:lodash-template/no-irregular-whitespacedisallow irregular whitespace outside the template tags.
:wrench:lodash-template/no-multi-spaces-in-scriptletdisallow multiple spaces in scriptlet. (ex. :ng: <% if···(test)···{ %>)
:wrench:lodash-template/scriptlet-indentenforce consistent indentation to scriptlet in micro-template tag.
:wrench:lodash-template/template-tag-spacingenforce unified spacing in micro-template tag. (ex. :ok: <%= prop %>, :ng: <%=prop%>)

Recommended with HTML template (Improve Readability with HTML template)

Enforce all the rules in this category and all the rules in Best Practices/Recommended categories with:

{
  "extends": "plugin:lodash-template/recommended-with-html"
}
Rule IDDescription
:wrench:lodash-template/attribute-name-casingenforce HTML attribute name casing. (ex. :ok: <div foo-bar> :ng: <div fooBar> <div FOO-BAR>)
:wrench:lodash-template/attribute-value-quoteenforce quotes style of HTML attributes. (ex. :ok: <div class="abc"> :ng: <div class='abc'> <div class=abc>)
:wrench:lodash-template/element-name-casingenforce HTML element name casing. (ex. :ok: <xxx-element> :ng: <xxxElement> <DIV>)
:wrench:lodash-template/html-closing-bracket-newlinerequire or disallow a line break before tag's closing brackets
:wrench:lodash-template/html-closing-bracket-spacingrequire or disallow a space before tag's closing brackets. (ex. :ok: <input> <input·/> :ng: <input·> <input/>)
:wrench:lodash-template/html-comment-content-newlinerequire or disallow a line break before and after HTML comment contents
:wrench:lodash-template/html-comment-spacingenforce unified spacing in HTML comment. (ex. :ok: <!-- comment -->, :ng: <!--comment-->)
:wrench:lodash-template/html-content-newlinerequire or disallow a line break before and after HTML contents
:wrench:lodash-template/html-indentenforce consistent HTML indentation.
:wrench:lodash-template/max-attributes-per-lineenforce the maximum number of HTML attributes per line
lodash-template/no-duplicate-attributesdisallow duplication of HTML attributes. (ex. :ng: <div foo foo>)
lodash-template/no-html-commentsdisallow HTML comments. (ex. :ng: <!-- comment -->)
:wrench:lodash-template/no-multi-spaces-in-html-tagdisallow multiple spaces in HTML tags. (ex. :ng: <input···type="text">)
:wrench:lodash-template/no-space-attribute-equal-signdisallow spacing around equal signs in attribute. (ex. :ok: <div class="item"> :ng: <div class = "item">)
lodash-template/no-warning-html-commentsdisallow specified warning terms in HTML comments. (ex. :ng: <!-- TODO:task -->)

Uncategorized

Rule IDDescription
lodash-template/no-template-tag-in-start-tagdisallow template tag in start tag outside attribute values. (ex. :ng: <input <%= 'disabled' %> >)
lodash-template/prefer-escape-template-interpolationsprefer escape micro-template interpolations. (ex. :ok: <%- ... %>, :ng: <%= ... %>)
<!--RULES_TABLE_END-->

Plugin Option

Suppress no-undef warnings in the template tag

Please set the global variable used in all templates as follows.

.eslintrc.*:

  {
      "settings": {
+         "lodash-template/globals": ["variableName"]
      }
  }

Please write the global comment in the file as follows for the variable to be used with a specific template.

+ <% /* global users */ %>
  <% for ( var i = 0; i < users.length; i++ ) { %>
    <li><a href="<%= users[i].url %>"><%= users[i].name %></a></li>
  <% } %>

Suppress reports for specific rules in template files

Please set as follows.

.eslintrc.*:

  {
      "settings": {
+         "lodash-template/ignoreRules": ["no-undef", "no-tabs"]
      }
  }

The ESLint standard suppression method can also be used by using template tag, as follows.

+ <% /* eslint no-ternary: 0 */ %>

Customize parser

For example, if you set Lodash templateSettings as follows,

_.templateSettings = {
    evaluate:    /{{([\s\S]+?)}}/g,
    interpolate: /{{=([\s\S]+?)}}/g,
    escape:      /{{-([\s\S]+?)}}/g
};

please set parserOptions(ex. .eslintrc.*) as follows.

      parserOptions: {
+         templateSettings: {
+             evaluate:    ["{{", "}}"],
+             interpolate: ["{{=", "}}"],
+             escape:      ["{{-", "}}"],
+         },
      },

For example, to parse like EJS, set as follows,

(If plugin:lodash-template/*** is set in extends, it is automatically applied to the extension .ejs.)

      parserOptions: {
+         templateSettings: {
+             evaluate:    [ ["<%", "<%_"], ["%>", "-%>", "_%>"] ],
+             interpolate: [  "<%-",        ["%>", "-%>", "_%>"] ],
+             escape:      [  "<%=",        ["%>", "-%>", "_%>"] ],
+             comment:     [  "<%#",        ["%>", "-%>", "_%>"] ],
+             literal:     [  "<%%" ],
+         },
      },

(This plugin do not provide complete support for EJS. e.g. the include directive.)

Customize target extensions

Please set .eslintrc.* as follows.

(For example, for EJS.)

+    "overrides": [
+        {
+            "files": ["*.ejs"],
+            "processor": "lodash-template/html"
+        }
+    ]

For JavaScript (TypeScript) Templates

(This is an experimental feature. Also check for known limitations.)

For example if you have a file like below.

/* eslint no-multi-spaces: error */
<% /* eslint lodash-template/no-multi-spaces-in-scriptlet: error */ %>

// if this plugin is not used, a parsing error will occur.
const obj    = <%= JSON.stringify(options     ) %>
//       ^^^^                            ^^^^^ 
//         |                              |
//         |          If you don't use `"plugin:lodash-template/recommended-with-script"`,
//         |          only the space after `options` is reported.
//         |
//         + When using `"plugin:lodash-template/recommended-with-script"`, the space after `obj` is also reported.

Playground on the Web

Configuring

Please set .eslintrc.* as follows.

+    "overrides": [
+        {
+            "files": ["**/your/templates/*.js"],
+            "extends": ["plugin:lodash-template/recommended-with-script"]
+        }
+    ]

If you do not want to use the included rules, set the details as follows.

    "overrides": [
        {
            "files": ["**/your/templates/*.js"],
-            "extends": ["plugin:lodash-template/recommended-with-script"],
+            "extends": ["plugin:lodash-template/base"],
+            "processor": "lodash-template/script",
+            "rules": {
+                "lodash-template/no-invalid-template-interpolation": "error"
+                ...
+            }
        }
    ]

If you want to use it with TypeScript, you need to configure parserOptions.

    "overrides": [
        {
-            "files": ["**/your/templates/*.js"],
+            "files": ["**/your/templates/*.ts"],
+            "parserOptions": {
+                 "parser": "@typescript-eslint/parser",
+                 "sourceType": "module"
+            },
            "extends": ["plugin:lodash-template/recommended-with-script"]
        }
    ]

FAQ

Known Limitations in Script Templates

Due to known limitations in script templates, you may need to rewrite some templates. Otherwise, you may not be able to use this plugin or some rules.

Parsing Error

Interpolation in the script template will try to replace it with an identifier and parse it. If you generate a complex script in interpolation, you may get a parsing error.

:+1: The following script can be parsed well.

let <%= idName %> = 42;
export { <%= idName %> };

:-1: The following script cannot be parsed well.

<%= 'let ' + idName %> = 42;
export { <%= idName %> };

False Positives in Some Rules

If you use branching in your template, the plugin will generate multiple script ASTs needed to cover all branches. (Then merge the results of validating these ASTs.)
This can confuse some rules and cause false positives.

However, this is necessary to avoid script parsing errors.

e.g.

Template:

const a = 'foo'
<% if (x) { %>
  const b = 1;
<% } else { %>
  const b = 2;
<% } %>

Generated Script 1:


const a = 'foo'

  const b = 1;



Generated Script 2:


const a = 'foo'



  const b = 2;

If we use the following script, it is a parsing error.


const a = 'foo'

  const b = 1;

  const b = 2; // <- Identifier 'b' has already been declared

The plugin also tries to generate scripts using branches that are as consistent as possible.

e.g.

Template:

<% if (x.foo) { %>
  const a = 'x.foo is true'
<% } %>
// ...
<% if (x.foo) { %>
  console.log(a)
<% } else { %>
  // process for x.foo is false
<% } %>

Generated Script 1:


  const a = 'x.foo is true'

// ...

  console.log(a)



Generated Script 2:




// ...



  // process for x.foo is false

However, branching conditions are compared using text, so even logically the same can be confusing.

e.g.

Template:

<% if (x['foo']) { %>
  const a = 'x.foo is true'
<% } %>
// ...
<% if (x.foo) { %>
  console.log(a)
<% } else { %>
  // process for x.foo is false
<% } %>

Generated Script 1:


  const a = 'x.foo is true'

// ...

  console.log(a)



Generated Script 2:


  const a = 'x.foo is true'

// ...



  // process for x.foo is false

This template gets an error 'a' is assigned a value but never used. from the no-unused-vars rule.

Editor Settings with HTML templates

About how to mark warnings on editor.

Migrations

Contributing

Welcome contributing!

Please use GitHub's Issues/PRs.

parserServices

Information provided by parserServices on this plugin

Development Tools

License

See the LICENSE file for license rights and limitations (MIT).