[英]Using javascript in Symfony2/Twig
I have a view called contact.html.twig. 我有一个名为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.
我想使用javascript来验证没有字段是空的,以及其他一些规则。 But I do not know where to put the .js with the definitions.
但我不知道在哪里放置.js的定义。 I do not know either how to call the .js script using the Twig notation.
我不知道如何使用Twig表示法调用.js脚本。
This is a generic answer for how to handle javascript... not specifically the validation part. 这是如何处理javascript的通用答案......而不是特别是验证部分。 The approach I use is to store individual functionality in separate JS files as plugins in the bundles
Resources/public/js
directory like so: 我使用的方法是将单独的功能存储在单独的JS文件中,作为bundle
Resources/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>
的末尾有一个块,用于$(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 %}
Isn't basic HTML5 functionality enough for your client side validation? 基本的HTML5功能不足以进行客户端验证吗? It is provided by the Form component.
它由Form组件提供。 You could also check:
你也可以检查一下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.