In Drupal 7, I had js-output template.

I define the template output as javascript. This is used for our front end person that can easily input javascript without touching backend.

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

In Drupal 8, I am trying to do the same thing by define twig file:

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

But when I put js in the customize_js_output field, as the following:

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


 $( document ).ready(function() {
        console.log( "ready!" );

Have jQuery is not defined or $ is not defined error. Got all of jQuery libraries load correct in the footer.

My question: Is this a good way to do it? If not, do you have any suggestions?

If i only want to write js inside my body field in the source or even php filter as content editor, can I do it?


In Drupal 8 it is not a good idea at all. You must define a library and put your js in a seperate file.

Here is a link to how to do it

Libraries in Drupal 8

Then if you want to write jquery you just need to add a dependency on core/jquery, also explained on the link.

If you want to attach a library to a twig function, you can do like this:

{# In a Twig template we attach the library. #}
{{ attach_library('modulename/libraryname') }}
|improve this answer|||||
  • 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 '18 at 16:05
  • I have updated my answer, now you can create a library and then the frontender just need to create the js file and then you can attach the library to the twig file. – user72672 Mar 26 '18 at 16:11
  • Did my updated answer work – user72672 Mar 26 '18 at 16:15
  • 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 '18 at 16:55
  • I don't think that you can do it without git. – user72672 Mar 26 '18 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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