symfony / stimulus-bridge

Stimulus integration bridge for Symfony projects
https://symfony.com/ux
75 stars 15 forks source link

Stimulus does't work on a fresh install of project #23

Closed vcastro45 closed 3 years ago

vcastro45 commented 3 years ago

Just starting a new project with Symfony 4.4 and Webpack Encore: Stimulus is here ! I’ve never used this and it look like it doesn’t works well for me. Is there something wrong in my code ? I juste have a Symfony controller that render base.html.twig and this file contains this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}{% endblock %}
        <link rel="stylesheet" href="{{ asset('build/app.css') }}">
        <script src="{{ asset('build/app.js') }}"></script>
        {% block javascripts %}{% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}
        <div data-controller="hello">
            <button data-action="click->hello#greet">Greet</button>
        </div>
    </body>
</html>

and the hello_controller.js contains this:

import { Controller } from 'stimulus'
export default class extends Controller {
  greet () {
    console.log('Hello, Stimulus!', this.element)
  }
  connect () {
    this.element.textContent = 'Hello Stimulus! Edit me in assets/controllers/hello_controller.js'
  }
}

In the browser, when I inspect the code, the bundled javascript code is well "rendered" but nothing happen when I click the "Greet" button.

tgalopin commented 3 years ago

Is this.element.textContent updated with the new text?

Also, you should probably use a the defer attribute on your script to execute it at the end of the page load.

vcastro45 commented 3 years ago

No, this.element.textContent is not updated with the new text. Even with the defer attribute on the script tag, it still not working.

tgalopin commented 3 years ago

Did you find the issue? What was it?

vcastro45 commented 3 years ago

I made a mistake: le way I was importing the js and css files was not the good one.

We have to use encore_entry_link_tags and encore_entry_script_tags:

        {% block stylesheets %}
            {{ encore_entry_link_tags('app') }}
        {% endblock %}
        {% block javascripts %}
            {{ encore_entry_script_tags('app') }}
        {% endblock %}