Skip to content

Linter Rule: Disallow ERB statements inside <script> tags

Rule: erb-no-statement-in-script

Description

Only insert expressions (<%= or <%==) inside <script> tags, never statements (<% %>). Statement tags inside <script> are likely a mistake, the author probably meant to use <%= %> to output a value.

Rationale

ERB statement tags inside <script> tags execute Ruby code but produce no output into the JavaScript context, which is rarely intentional. If you need to interpolate a value into JavaScript, use expression tags (<%= %>) with .to_json for safe serialization. If you need conditional logic, restructure the template to keep control flow outside the <script> tag.

Exceptions: <% end %> is allowed (for closing blocks), ERB comments (<%# %>) are allowed, and <script type="text/html"> allows statement tags since it contains HTML templates, not JavaScript.

Examples

✅ Good

erb
<script>
  var myValue = <%== value.to_json %>;
  if (myValue) doSomething();
</script>
erb
<script type="text/template">
Avoid using `text/template` as the `type` attribute for the `<script>` tag. Must be one of: `text/javascript` or blank. (html-allowed-script-type)
<%= ui_form do %>
Unsafe ERB output in `<script>` tag. Use `.to_json` to safely serialize values into JavaScript. (erb-no-unsafe-script-interpolation)
<div></div> <% end %> </script>
erb
<script type="text/javascript">
  <%# comment %>
</script>
erb
<script type="text/html">
Avoid using `text/html` as the `type` attribute for the `<script>` tag. Must be one of: `text/javascript` or blank. (html-allowed-script-type)
<% if condition %> <p>Content</p> <% end %> </script>

🚫 Bad

erb
<script>
  <% if value %>
Avoid `<% %>` tags inside `<script>`. Use `<%= %>` to interpolate values into JavaScript. (erb-no-statement-in-script)
doSomething(); <% end %> </script>
erb
<script type="text/javascript">
  <% if foo? %>
Avoid `<% %>` tags inside `<script>`. Use `<%= %>` to interpolate values into JavaScript. (erb-no-statement-in-script)
bla <% end %> </script>

References

Released under the MIT License.