简体   繁体   中英

Symfony + Webpack using node packages inside templates

I am trying to implement Webpack Encore in my Symfony Project. I just added SweetAlert2 with node ( npm i sweetalert2 --dev ).

My "problem" is that I don't realize how to properly use this package once installed. I've been reading other questions but I don't understand where do I need to import it.

So far I've tried:

  1. Creating a file inside /assets/js/swal.js . Also, I have tried with ES5 as well:
import Swal from 'sweetalert2';

export const swal = (message, type) => {
    Swal.fire({
        position: 'top-end',
        icon: type,
        title: message,
        showConfirmButton: false,
        timer: 1500
    });
}
  1. Add it to webpack.config.js as an Entry Point:
.addEntry('app', './assets/js/app.js')
.addEntry('swal', '/assets/js/swal.js')
  1. Add it as an asset to the template with <script src="{{ asset('js/swal.js') }}"></script> . Maybe is worth to mention that I did try all the paths and PHPStorm does not recognize any of them.

  2. Print the function or class inside Twig template:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}{% endblock %}

        {{ encore_entry_link_tags('app') }}
    </head>
    <body>
        {% block body %}{% endblock %}

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

        {% if app.flashes is not empty %}
            <script>
                console.log(swal);
            </script>
        {% endif %}
    </body>
</html>

I also tried importing it with require() but require is not idefined.

What should I do to implement this function and render it in the Twig template?

You can only import modules inside javascript (or typescript, etc) files.

let's say you have a function inside the script of the twig template:

<script>
  function doSomethingBasic() {
     // do your thing here, then alert the user using Swal
  }
</script>

What you should do is export everything inside the javascript tag into a new.js file, inside the /assets folder.

After you create a new file inside the /assets folder with any name you want, you should add that entry to the webpack.config.js.

For example: You created the newJavascript.js inside /assets.

Inside webpack.config.js:

.addEntry(`literallyAnyName`, `/assets/newJavascript.js`)

Then, in your twig template, substitute your script tags for this (must be the name you put in the webpack.config.js, in this case literallyAnyName):

{{ encore_entry_script_tags('literallyAnyName') }}

With this, you can import Swal in your newJavascript.js

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}
          {{ encore_entry_link_tags('literallyAnyName') }}
        {% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}

        {% set flashes = [] %}
        {% if app.flashes is not empty %}
          {% for label,message in app.flashes %}
             {% set flashes = flashes|merge([{
               'type': label,
               'message': message
             }]) %}
          {% endfor %}
        {% endif %}
            <div id="flashes" data-flashes="{{ flashes|json_encode|e('html_attr') }}"></div>
        {% block javascripts %}
          {{ encore_entry_script_tags('literallyAnyName') }}
        {% endblock %}
    </body>
</html>

newJavascript.js:

const flashes = JSON.parse(document.querySelector(`#flashes`).dataset.flashes);

// Maybe reduce the flash object into one message using flashes.reduce;
if(flashes.length > 0) {

  const msg = flashes.reduce(/* your logic here */);

  Swal.fire({
    position: 'top-end',
    icon: type,
    title: msg,
    showConfirmButton: false,
    timer: 1500
  });

}

This will trigger the second the page loads. You can make a button trigger as well if you need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM