计算树枝中的多值字段值


9

我想计算试过的枝条tempalate中无限字段的值数量

{{ node.field_mytext.count }} => 面对错误

然后再尝试

{{ content.field_mytext.count }}=> 没有任何回报

(在这种方法中,我检查了我的字段不在禁用字段中是显示管理器)。


我的问题是如何计算Twig中一个字段的项目数?

我希望我面对的解决方案期望这些解决方案:D


您是否尝试过{{content.field_mytext | 长度 }}?
大卫·麦克史密斯,2016年

Answers:


14

{{node.field_mytext.count}} =>遇到错误

这是行不通的,因为count树枝策略中不允许使用该方法:

core / lib / Drupal / Core / Template / TwigSandboxPolicy.php

{{content.field_mytext | 长度 }}?

这是行不通的,因为它content是具有很多其他键的渲染数组。

这有效:将字段转换为数组和计数

{{ node.field_mytext.getvalue | length }}

您可能还可以使用foreach循环来完成此操作,但这对于此特定用途而言是更干净的。
没有Sssweat

6

最简单的方法是获取['#items']|length。我一直都在计算项目以查看更多实例以及加载滑块时。

{{ content.field_mytext['#items']|length }}

4

我使用了自己的Twig过滤器来支持实体字段,使用它您可以将字段用作本机数组:

{{ content.field_mytext|length }}

要么

{{ content.field_mytext|first|value }}

要么

{% if content.field_mytext is empty %}

您可以通过自定义模块轻松添加自己的Twig过滤器。您可以在此处了解更多信息:drupal.org/docs/8/creating-custom-modules。简而言之,您需要创建一个模块目录,例如path/to/drupal/modules/custom/common/,在common.info.yml其中放置模块定义和common.services.yml服务定义(请参阅代码中的注释),然后将我的代码放置到/path/to/drupal/modules/custom/common/src/TwigExtension.php

<?php
namespace Drupal\common;

use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\TypedData\ComplexDataInterface;

/**
 * A class providing Twig extensions.
 *
 * This provides a Twig extension that registers various Field-API-specific
 * extensions to Twig, overriding empty and array related filters.
 *
 * Don't forget about common.services.yml
 * services:
 *   common.twig.TwigExtension:
 *     class: Drupal\common\TwigExtension
 *     tags:
 *       - { name: twig.extension }
 *
 * Usage (in *.html.twig file):
 *   - check is field empty {% if content.field_foo is empty %}
 *   - get field first value {{ content.field_foo|first|value }}
 */
class TwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getTests() {
    return [
      new \Twig_SimpleTest('empty', [$this, 'twigEmptyField']),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFilters() {
    return [
      new \Twig_SimpleFilter('length', [$this, 'twigLengthFilter'], ['needs_environment' => TRUE]),
      new \Twig_SimpleFilter('slice', [$this, 'twigSlice'], ['needs_environment' => TRUE]),
      new \Twig_SimpleFilter('first', [$this, 'twigFirst'], ['needs_environment' => TRUE]),
      new \Twig_SimpleFilter('last', [$this, 'twigLast'], ['needs_environment' => TRUE]),
      new \Twig_SimpleFilter('value', [$this, 'twigFieldValue']),
    ];
  }

  /**
   * Check if value is field item object.
   *
   * @param mixed $value
   *   Mixed Twig variable.
   *
   * @return \Drupal\Core\Field\FieldItemListInterface|mixed
   *   FieldItemListInterface or same value as passed.
   */
  private function checkItems($value) {
    if (is_array($value) && !empty($value['#items']) && $value['#items'] instanceof FieldItemListInterface) {
      return $value['#items'];
    }
    return $value;
  }

  /**
   * Get field item value.
   *
   * @param object $field
   *   Field object.
   *
   * @return array|mixed
   *   List of values or value.
   */
  public function twigFieldValue($field) {
    if ($field instanceof FieldItemInterface) {
      $prop = $field->mainPropertyName();
      $value = $field->getValue();
      return $prop ? $value[$prop] : $value;
    }
    if ($field instanceof FieldItemListInterface) {
      $value = [];
      foreach ($field as $item) {
        $value[] = $this->twigFieldValue($item);
      }
      return $value;
    }
    return '';
  }

  /**
   * Checks if a variable is empty.
   *
   * @see twig_test_empty
   */
  public function twigEmptyField($value) {
    $value = $this->checkItems($value);
    if ($value instanceof ComplexDataInterface) {
      return $value->isEmpty();
    }
    // Return TRUE, because there is no data only cache and weight.
    elseif (!is_object($value) && isset($value['#cache']) && count($value) == 2) {
      return TRUE;
    }
    return twig_test_empty($value);
  }

  /**
   * Returns the length of a variable.
   *
   * @param \Twig_Environment $env
   *   Twig environment.
   * @param mixed $item
   *   A variable.
   *
   * @return mixed
   *   The first element of the item.
   *
   * @see twig_length_filter
   */
  public function twigLengthFilter(\Twig_Environment $env, $item) {
    $item = $this->checkItems($item);
    return twig_length_filter($env, $item);
  }

  /**
   * Slices a variable.
   *
   * @param \Twig_Environment $env
   *   Twig environment.
   * @param mixed $item
   *   A variable.
   * @param int $start
   *   Start of the slice.
   * @param int $length
   *   Size of the slice.
   * @param bool $preserveKeys
   *   Whether to preserve key or not (when the input is an array)
   *
   * @return mixed
   *   The first element of the item.
   *
   * @see twig_slice
   */
  public function twigSlice(\Twig_Environment $env, $item, $start, $length = NULL, $preserveKeys = FALSE) {
    $item = $this->checkItems($item);
    return twig_slice($env, $item, $start, $length, $preserveKeys);
  }

  /**
   * Returns the first element of the item.
   *
   * @param \Twig_Environment $env
   *   Twig environment.
   * @param mixed $item
   *   A variable.
   *
   * @return mixed
   *   The first element of the item.
   *
   * @see twig_first
   */
  public function twigFirst(\Twig_Environment $env, $item) {
    $item = $this->checkItems($item);
    return twig_first($env, $item);
  }

  /**
   * Returns the last element of the item.
   *
   * @param \Twig_Environment $env
   *   Twig environment.
   * @param mixed $item
   *   A variable.
   *
   * @return mixed
   *   The first element of the item.
   *
   * @see twig_last
   */
  public function twigLast(\Twig_Environment $env, $item) {
    $item = $this->checkItems($item);
    return twig_last($env, $item);
  }

}

0

使用长度过滤器

{{ content.field_mytext | length }} 

4
返回错误值!!!,我的字段很长,我在那里有4个项目,但返回20!
Yusef

1
这可以(取决于情况)可以返回正确的值,但这是不正确的答案。
aydow19年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.