Search code examples
javascripttwigphpstormcraftcms

Language Injection Rule PhpStorm -> JavaScript in Twig Block


I'm working with CraftCMS, which uses Twig. One of the methods I use to add JS is e.g.

{% js at endBody %}
    console.log('I am JavaScript');
{% endjs %}

I want to have it permanently highlighted as JavaScript, and not have to reinject it every time I open PhpStorm again.

According to https://www.jetbrains.com/help/phpstorm/using-language-injections.html#configure-injection-rules I need to add an injection rule. So I went to

  1. Editor
  2. Language Injections
  3. Add (+)
  4. Generic Twig
  5. (See image)

Language Injection Settings in PhpStorm

What do I have to enter in this window though? I'm a bit lost here. Any help is valuable :)


Solution

  • Sure, just add a pattern for matching your custom js Twig tag:

    + twigCustomStatement("js")
    

    https://www.jetbrains.com/help/phpstorm/language-injection-settings-generic-twig.html

    P.S. PhpStorm already has a bundled similar rule for script Twig tag. It does exactly the same. The only difference is in the tag name: script versus your js.

    enter image description here


    The final result (notice the light green background that indicates the Language Injection rule in action + syntax colors for JS code; shows both your tag and bundled one):

    enter image description here
    (NOTE: copy+pasting in the file, re-opening the file or the whole project/IDE may be needed to have new Injection rule to be applied)

    Proof that it's a JavaScript:

    enter image description here