Use function Javascript on TWIG page using WebPack Encore and Symfony 4
Asked Answered
M

3

5

i'm using Symfony 4.2 and i use last WebPack Encore.

I have issu because i need to use function from my javascript on my twig template, but this never work.

I always have same problem:

Uncaught ReferenceError: consoleText is not defined at (index):17

assets/js/app.js:

require('../css/app.css');
const $ = require('jquery');
global.$ = global.jQuery = $;

assets/js/myFunctions.js

const consoleText = function (log = "Auncun log") {
console.log(log);
};

module.exports = {
    consoleText: consoleText
};

webpack.config.js

var Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .addEntry('app', './assets/js/app.js')
    .enableSingleRuntimeChunk()
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    .autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

I need to get access to my function consoleText() outside my file.

If i want to get access on javascript file, this work. Exemple: In my app.js i can add:

let myTest = require('./myFunctions');
myTest.consoleText('Blablabla');

this work fine after compilation.

BUT i need to get access this function on my twig template (home.html.twig)

In my base.html.twig i called my script file with:

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


    // NEED HERE USE MY FUNCTION LIKE:
    {{ encore_entry_script_tags('myFunctions') }}
    <script>
        consoleText("This don't work");
    </script>
{% endblock %}

my consoleTest() function don't work and i don't understand why. I try to use Module.export, and tried to use lot of thinks but i don't know why i can't call my function on my twig template, so i need your help.

Thank you

Monamonachal answered 14/2, 2019 at 10:33 Comment(0)
S
5

@Eöras Think reverse... Pass twig to js instead of using js on twig to pass twig variables.

https://symfony.com/doc/current/frontend/encore/server-data.html

example: https://gist.github.com/MkLHX/d4d38f4fd1fe702fdb9b2a0077ca9c81

Shamrock answered 24/7, 2019 at 9:38 Comment(0)
C
4

It's not working and it's as expected, because part of webpack job is to encapsulate the script content so you can't access it globally, letting you only call it once you have imported it. A way around that could be :

window.consoleText = function (log = "Auncun log") {
console.log(log);
};

but it would require your script to be imported by any other script before the inline script is running

Crumb answered 14/2, 2019 at 10:50 Comment(2)
OK, but suddenly when we have some functions to run anywhere on our site, which take into account twig variables, it's complicated now. :/Neuroticism
I don't think you are supposed to be using twig with webpack, especially if it contains scripts / business data. Webpack is used most of the times with a real UI framework like React or Angular. Tbh, I don't really see the point of this encore webpack thing since PHP isnt really suited for that kind of usage anywayCrumb
C
0

install gulp in global and in your project as explained here https://gulpjs.com/docs/en/getting-started/quick-start/

Add your js file in assets/js directory. ex in myJSFile.js

const foo = () => {
    console.warn("Foo")
}

Then create a gulpfile.js at the root of your project with the content below

const { src, dest } = require('gulp');
const gulpif = require('gulp-if');
const uglify = require('gulp-uglify');

function isJavaScript(file) {
    // Check if file extension is '.js'
    return file.extname === '.js';
}

exports.default = function() {
    // Include JavaScript and CSS files in a single pipeline
    return src(
        ['./assets/js/myJSFile.js']
    )
        // Only apply gulp-uglify plugin to JavaScript files
        .pipe(gulpif(isJavaScript, uglify()))
        .pipe(dest('public/build'));
}

From the twig file ex index.twig.html in javacript block do so.

{% block javascript %}
  <script src={{ asset('build/myJSFile.js') }}></script>
  <script>
     foo()
</script>
{% endblock %}

Then in the console of your ide or another console making sure you are in the root directory of your project => run

gulp
Cassiani answered 25/12, 2023 at 20:30 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.