In Drupal 7, I had a template containing JavaScript code.

<?php if(isset($content['field_custom_javascript'])) print $content['field_custom_javascript']['#items'][0]['value']; ?>

In Drupal 8, I am trying to achieve the same in a template file.

{% if content.field_custom_javascript is not empty %}
    {{ content.field_custom_javascript }}
{% endif %}

When I put this JavaScript code in that field, I get an error about jQuery not being defined.

(function ($, Drupal) {
  $(document).ready(function() {
    console.log( "ready!" );
})(jQuery, Drupal);

Is this a good way to do it, or do you have any suggestion?

1 Answer 1


In Drupal 8, it's not a good idea at all. You must define a library and put the JavaScript code in a separate file, following what described in Adding assets (CSS, JS) to a Drupal theme via *.libraries.yml.

If the JavaScript code uses jQuery, core/jquery must be added as library dependency.

If you want to attach a library in a template file, the following code achieves that.

{{ attach_library('modulename/libraryname') }}
  • But the frontend person do not have the access to the git repo or can not push the code. Is there any way to solve this kind of problem? Frontend person write bunch of js for any certain pages without touch backend. Or is there any contribute modules suggestions that i can use. Thanks in advance.
    – LisaH1110
    Mar 26, 2018 at 16:05
  • Thanks, so it still need to do the git push every time frontenders create js file. Is there any way that they can do it by themselves without git? Thanks in advance.
    – LisaH1110
    Mar 26, 2018 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.