[英]How to call function in twig in Symfony2?
In my model (Task) I have a function: 在我的模型(任务)中,我有一个函数:
public function isTaskOverdue()
{
if ("now"|date('Y-m-d') > task.deadline|date('Y-m-d')){
return false;
} else{
return true;
}
}
In twig (edit) I want to display form: 在树枝(编辑)中,我想显示表格:
{% extends 'base.html.twig' %}
{% block title %}app:Resources:Task:edit{% endblock %}
{% block body %}
{{ form(form) }}
{% endblock %}
I want to display form, if this function return true. 我想显示表单,如果此函数返回true。 How can I call this function in twig?
如何在树枝中调用此功能?
Pass the task entity to twig and call method from object task : 将任务实体传递给twig并从对象task调用方法:
{% if task.isTaskOverdue %}
{{ form(form) }}
{% endif %}
I think it should be your controller that receives the function result and display the form or not depending on it. 我认为应该是您的控制器接收函数结果并显示表格,还是不依赖它。
Also you can write your function like so : 您也可以这样编写函数:
public function isTaskOverdue()
{
return ("now"|date('Y-m-d') > task.deadline|date('Y-m-d'));
}
Pass the task entity to twig and do : 将任务实体传递给树枝并执行以下操作:
{% extends 'base.html.twig' %}
{% block title %}app:Resources:Task:edit{% endblock %}
{% block body %}
{% if "now"|date("Ymd") <= task.deadline|date("Ymd") %}
{{ form(form) }}
{% endif %}
{% endblock %}
But, caution : 但是,请注意:
If you just not display the form, there is a security issue, because if an attacker submit the form from an self rebuilded HTML page, your controller will receive the form data and apply it. 如果您仅不显示表单,则存在安全问题,因为如果攻击者从自行重建的HTML页面提交表单,则您的控制器将接收并应用表单数据。
So I would do the check in the controller, and only create and pass the form to the twig template if the condition is true. 因此,我将在控制器中进行检查,如果条件为真,则仅创建表格并将其传递给树枝模板。
Then, in twig you can use : 然后,可以在树枝中使用:
{% if form is defined %}
{{ form(form) }}
{% endif %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.