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

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

问题描述

在View模块的一个覆盖模板(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) }}

打印null

我想要原始以根据字段的值构建文件路径。

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" /> 

为什么这么难?

推荐答案

与其在小树枝文件中构建东西,不如对其进行预处理,然后在小树枝文件中引用新变量。

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-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天全站免登陆