I am trying to create a basic jQuery function on my twig template but I can't seem to get it to work. Can someone please help me!?

My Twig File is as follows:

{% block javascripts %}
    {#if you include jquery here, the scripts that need jquery will fail because jquery exists since this point !#}
    <script type="text/javascript" src="{{ asset('js/jquery.min.js') }}">
    $(".nav li.expanded").hover(
      alert("Inside Function");
      alert("Outside Function");
{% endblock %}
{% set heading_id = attributes.id ~ '-menu'|clean_id %}
<nav role="navigation" aria-labelledby="{{ heading_id }}"{{ attributes.removeClass('clearfix')|without('role', 'aria-labelledby') }}>
  {# Label. If not displayed, we still provide it for screen readers. #}
  {% if not configuration.label_display %}
    {% set title_attributes = title_attributes.addClass('sr-only') %}
  {% endif %}
  <h2{{ title_attributes.setAttribute('id', heading_id) }}>{{ configuration.label }}</h2>

  {% block content %}
    {{ content }}
  {% endblock %}

Error Output:

The website encountered an unexpected error. Please try again later.</br></br><em class="placeholder">Twig_Error_Syntax</em>: Unknown &quot;asset&quot; function. in <em class="placeholder">Twig_ExpressionParser-&gt;getFunctionNodeClass()</em> (line <em class="placeholder">38</em> of <em class="placeholder">themes/custom/navy/templates/block/block--system-menu-block--main.html.twig</em>). <pre class="backtrace">Twig_ExpressionParser-&gt;getFunctionNode(&#039;asset&#039;, 38) (Line: 162)
Twig_ExpressionParser-&gt;parsePrimaryExpression() (Line: 102)
Twig_ExpressionParser-&gt;getPrimary() (Line: 55)
Twig_ExpressionParser-&gt;parseExpression() (Line: 149)
Twig_Parser-&gt;subparse(Array, 1) (Line: 40)
Twig_TokenParser_Block-&gt;parse(Object) (Line: 192)
Twig_Parser-&gt;subparse(NULL, ) (Line: 105)
Twig_Parser-&gt;parse(Object) (Line: 716)
Twig_Environment-&gt;parse(Object) (Line: 774)
Twig_Environment-&gt;compileSource(Object) (Line: 452)
Twig_Environment-&gt;loadTemplate(&#039;themes/custom/navy/templates/block/block--system-menu-block--main.html.twig&#039;) (Line: 64)
twig_render_template(&#039;themes/custom/navy/templates/block/block--system-menu-block--main.html.twig&#039;, Array) (Line: 384)
Drupal\Core\Theme\ThemeManager-&gt;render(&#039;block&#039;, Array) (Line: 437)
Drupal\Core\Render\Renderer-&gt;doRender(Array) (Line: 450)
Drupal\Core\Render\Renderer-&gt;doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer-&gt;render(Array) (Line: 490)
Drupal\Core\Template\TwigExtension-&gt;escapeFilter(Object, Array, &#039;html&#039;, NULL, 1) (Line: 182)
__TwigTemplate_7206b6943ab6709e209af4c71d787052441f5e0fc6966fa51bfb08236a79f5ef-&gt;block_main(Array, Array) (Line: 215)
Twig_Template-&gt;displayBlock(&#039;main&#039;, Array, Array) (Line: 65)
__TwigTemplate_7206b6943ab6709e209af4c71d787052441f5e0fc6966fa51bfb08236a79f5ef-&gt;doDisplay(Array, Array) (Line: 432)
Twig_Template-&gt;displayWithErrorHandling(Array, Array) (Line: 403)
Twig_Template-&gt;display(Array) (Line: 411)
Twig_Template-&gt;render(Array) (Line: 64)
twig_render_template(&#039;themes/custom/navy/templates/page/page.html.twig&#039;, Array) (Line: 384)
Drupal\Core\Theme\ThemeManager-&gt;render(&#039;page&#039;, Array) (Line: 437)
Drupal\Core\Render\Renderer-&gt;doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer-&gt;render(Array) (Line: 490)
Drupal\Core\Template\TwigExtension-&gt;escapeFilter(Object, Array, &#039;html&#039;, NULL, 1) (Line: 90)
__TwigTemplate_1851d7a76e53df9c9a6b9fa5328c4c7d784772b2109ead0be693668c41ae4e88-&gt;doDisplay(Array, Array) (Line: 432)
Twig_Template-&gt;displayWithErrorHandling(Array, Array) (Line: 403)
Twig_Template-&gt;display(Array) (Line: 411)
Twig_Template-&gt;render(Array) (Line: 64)
twig_render_template(&#039;themes/contrib/bootstrap/templates/system/html.html.twig&#039;, Array) (Line: 384)
Drupal\Core\Theme\ThemeManager-&gt;render(&#039;html&#039;, Array) (Line: 437)
Drupal\Core\Render\Renderer-&gt;doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer-&gt;render(Array) (Line: 147)
Drupal\Core\Render\MainContent\HtmlRenderer-&gt;Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer-&gt;executeInRenderContext(Object, Object) (Line: 148)
Drupal\Core\Render\MainContent\HtmlRenderer-&gt;renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber-&gt;onViewRenderArray(Object, &#039;kernel.view&#039;, Object)
call_user_func(Array, Object, &#039;kernel.view&#039;, Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-&gt;dispatch(&#039;kernel.view&#039;, Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel-&gt;handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel-&gt;handle(Object, 1, 1) (Line: 67)
Drupal\simple_oauth\HttpMiddleware\BasicAuthSwap-&gt;handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session-&gt;handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle-&gt;handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache-&gt;pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache-&gt;handle(Object, 1, 1) (Line: 40)
Drupal\jsonapi\StackMiddleware\FormatSetter-&gt;handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware-&gt;handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware-&gt;handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel-&gt;handle(Object, 1, 1) (Line: 666)
Drupal\Core\DrupalKernel-&gt;handle(Object) (Line: 19)
  • Says the error right there, asset() is not defined. I don't see that function in the Twig docs either. twig.symfony.com/doc/1.x. Why not just do it the right way with a Javascript file, then attach the library either in the Twig file or a preprocess hook? – Kevin Nov 19 '18 at 19:31
  • @Kevin I copied that from some previous post to see if it would work. Sorry I didn't remove it, but when you remove it the page will load but no js will run – B. Cratty Nov 19 '18 at 19:39
  • I don't know what that means. Read the docs about how to include Javascript in twig templates. – Kevin Nov 19 '18 at 19:47
  • @Kevin Let me reword that, I can get js to run but I am unable to get jQuery to work – B. Cratty Nov 19 '18 at 20:09
  • Seems I was too quick to close this, sorry @B.Cratty. – Clive Nov 19 '18 at 20:24

There are a few things going wrong:

  1. jQuery is in no conflict mode, so there's no global $. A common pattern to provide it in the manner you're accustomed is:

    (function($) {
  2. Assuming you use a sensible theme, jQuery isn't actually available at that point in the document. The <script> tags are before the </body> tag.

  3. You're not looking at your browser console, which would have told you much of this ;)

To include JS in a template, you should create a library, and attach it either in a preprocess function, or directly in the template itself with:

| improve this answer | |
  • sorry to vote for the duplicate while you were answering, luckily you can answer even when a question is closed ;-). The duplicate has a solution for inline jquery, but I agree, normally you shouldn't do this. – 4k4 Nov 19 '18 at 21:39
  • No problem, there's a grace period if you start answering before it's closed (which I did and then left it for a bit to sort the kids out). No dark mod arts ;) I think merging this and the duplicate might be the best thing to do eventually so everything's in one place, I'll wait for a bit and see what the OP of this one comes back with – Clive Nov 19 '18 at 22:34
  • @Clive So I just needed some help with the exact steps of making my own theme js. So lets say I have testTheme.theme file and I want to create a testTheme.js. Would I just create the file and add it in the same folder and thats it? – B. Cratty Nov 27 '18 at 15:37

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