Eöras
Eöras

Reputation: 105

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

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

Upvotes: 5

Views: 6791

Answers (3)

momoSakhoMano
momoSakhoMano

Reputation: 77

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

Upvotes: 0

Mickael Lehoux
Mickael Lehoux

Reputation: 131

@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

Upvotes: 5

Vinz243
Vinz243

Reputation: 9948

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

Upvotes: 4

Related Questions