在 Drupal 8 视图模板中访问原始数据 [英] Acces raw data in Drupal 8 view template

查看:28
本文介绍了在 Drupal 8 视图模板中访问原始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在视图模块的覆盖模板 (views-view-field.html.twig) 中,我试图访问字段的原始数据.

In a overridden template of the View module (views-view-field.html.twig), i'm trying to access to the raw data of a field.

在doc文件中,我们可以读到:

In the doc file, we can read this:

 * Available variables:
...
 * - fields: A list of fields, each one contains:
...
 *   - raw: The raw data for the field, if it exists. This is NOT output safe.
...

但它总是空的.

{{ dump(fields.field_myfieldname) }}

打印对象(stdClass)[1899] ...

print object(stdClass)[1899] ...

{{ dump(fields.field_myfieldname.raw) }}

打印空

我希望原始文件根据字段的值构建文件路径.

I want the raw to build a file path from the value of a field.

为什么是空的?还有其他方法可以获取模板中字段的原始数据吗?

Why it's empty? Is there an other whay to get the raw data of a field in my template ?

我正在尝试做这样的事情:

Edit : I'm trying to do something like this:

 <img src="/path/to/image/{{ fields.title.raw | escape('uri')}}.jpg" /> 

为什么这么难?

推荐答案

与其在 twig 文件中构建内容,不如对数据进行预处理,然后在 twig 文件中引用新变量.

Instead of building stuff in the twig files, you should instead preprocess your data and then reference your new variable in your twig file.

例如,如果您的自定义主题名为 mytheme,则在您的 mytheme.theme 文件中,添加以下函数

For example, if your custom theme is called mytheme, then in your mytheme.theme file, add the following function

function mytheme_preprocess_field(&$variables, $hook) {

  if( $variables['field_name'] === 'field_myfieldname') {

    // manipulate the data and return it in a variable.

    $data = $variables['items'][0]['content']['#context']['value'];

    $variables['customfield'] = "Whatever you want, can be HTML";

    }
}

然后在您的 field--node--field-myfieldname.html.twig 文件中,调用您的新变量

Then in your field--node--field-myfieldname.html.twig file, call your new variable

{{ customfield }}

如果您要返回 html,请像这样调用您的新变量

If you are returning html, call your new variable like so

{{ customfield|raw }}

这篇关于在 Drupal 8 视图模板中访问原始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆