在 Symfony2/Twig 中使用 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11297594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:21:52  来源:igfitidea点击:

Using javascript in Symfony2/Twig

javascriptsymfonytwig

提问by camelCase

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.

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

回答by MDrollette

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/jsdirectory like so:

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

(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:

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

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

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

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

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

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

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

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

回答by Codium

Isn't basic HTML5 functionality enough for your client side validation? It is provided by the Form component. You could also check:

基本的 HTML5 功能还不足以进行客户端验证吗?它由 Form 组件提供。您还可以检查: