简体   繁体   中英

Call a function from an external JavaScript file in href with Symfony and Twig

I'm trying to call a function from an external JavaScript file in href with Symfony and Twig.

Here is my JavaScript file pm.js :

function test(id) {
    alert(id);
}

And here is my template :

{# templates/pm/pm.html.twig #}
{% extends 'base.html.twig' %}

{% block title %}{{ parent() }} | Private messaging{% endblock %}

{% block body %}
    (...)
    <a href="javascript:test({{ message.id }});">test</a>
    (...)
{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script src="{{ asset('build/js/pm.js') }}"></script>
{% endblock %}

How can I do that? Thanks for help.

That happens because you are using a compiled pm.js javascript file (that's why it lives in build/js I guess). If you just have placed pm.js in your public js folder without compiling it your code will be good to work as it is.

Your problem is that your function after the compilation is not a global function. You could overcome this with several ways, the most simple of them being:

window.test = function test(id) {
    alert(id);
}

Just assign your function test() to a window variable window.test and it will work.

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