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
@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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With