简体   繁体   English

使用细枝宏设置变量

[英]Set a Variable with a Twig Macro

I have to set a variable with a macro, that returns a number, so I have this macro: 我必须用一个宏设置一个变量,该变量返回一个数字,所以我有这个宏:

{% import _self as self %}

{% macro function_size(field) %}

  {% import _self as self %}

  {# initial Setup #}
  {% set field_length = 0 %}

  {# Field #}
  {% for key, value in field %}
    {% if not (key starts with "#") %}
      {% set field_length = field_length + 1 %}
    {% endif %}
  {% endfor %}

  {{ field_length }}

{% endmacro %}

The Macro loops through the entries of a field and returns the count of values, that don't start with "#". 宏在字段的各个条目之间循环,并返回不以“#”开头的值的计数。

So I set a variable with that value: 因此,我用该值设置了一个变量:

{% set image_size       = self.function_size(content.field_teaser_image) %}

ATTENTION: With this you will set the Variable with Twig Markup. 注意:这样,您将使用Twig标记设置变量。 (You can see that when you debug the variable afterwards.) (您可以在以后调试变量时看到。)

To get a number/integer as value you have to convert it to a String (that will be interpreted as a number if you calculate with it) 要获取数字/整数作为值,您必须将其转换为字符串(如果您使用它进行计算,它将被解释为数字)

{% set image_size       = image_size.__toString %}

With this I set the Variable successfully with a macro. 这样,我可以通过宏成功设置变量。

My Question: Is this a bad practice, are there better ways how to set an Variable? 我的问题:这是不好的做法吗,有没有更好的方法来设置变量?

Thank you! 谢谢!

Two ways to set variables for twig are fine in my opinion. 我认为,有两种方法可以为细枝设置变量。 1. Use theme and other hooks (inside theme or any module) and pass variable from php, 2. create twig extension/filter 1.使用主题和其他挂钩(在主题或任何模块内部)并从php传递变量,2.创建树枝扩展/过滤器

Examples: 例子:

Filter: http://leopathu.com/content/create-custom-twig-filter-drupal-8 过滤器: http : //leopathu.com/content/create-custom-twig-filter-drupal-8

Extension: 延期:

http://symfony.com/doc/current/templating/twig_extension.html http://symfony.com/doc/current/templating/twig_extension.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM