在 Symfony2/Twig 中使用 javascript

2022-01-22 00:00:00 javascript symfony twig

我有一个名为contact.html.twig 的视图.它有一个带有一些文本字段的表单.我想使用 javascript 来验证所有字段都不是空的,以及其他一些规则.但我不知道将 .js 与定义放在哪里.我也不知道如何使用 Twig 表示法调用 .js 脚本.

I have a view called contact.html.twig. It has a form with some textfields. I want to use javascript to validate that none of the fields are empty, as well as some other rules. But I do not know where to put the .js with the definitions. I do not know either how to call the .js script using the Twig notation.

推荐答案

这是一个关于如何处理 javascript 的通用答案……而不是验证部分.我使用的方法是将单独的功能存储在单独的 JS 文件中作为 bundles Resources/public/js 目录中的插件,如下所示:

This is a generic answer for how to handle javascript... not specifically the validation part. The approach I use is to store individual functionality in separate JS files as plugins in the bundles Resources/public/js directory like so:

(function ($) {

    $.fn.userAdmin = function (options) {
        var $this = $(this);

        $this.on('click', '.delete-item', function (event) {
            event.preventDefault();
            event.stopPropagation();

            // handle deleting an item...
        });
    }
});

然后我使用资产将这些文件包含在我的基本模板中:

I then include these files in my base template using assetic:

{% javascripts
    '@SOTBCoreBundle/Resources/public/js/user.js'
%}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}

在我的基本模板中,我在 <body> 的末尾有一个块用于 $(document).ready();

In my base template I have a block at the end of <body> for a $(document).ready();

<script>
    $(document).ready(function () {
        {% block documentReady %}{% endblock documentReady %}
    });
</script>
</body>

然后在具有用户管理员"功能的页面中,我可以像这样调用 userAdmin 函数:

Then in my page that has the "user admin" functionality I can call the userAdmin function like so:

{% block documentReady %}
    {{ parent() }}
    $('#user-form').userAdmin();
{% endblock documentReady %}

相关文章