问题
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.
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.
...
but it's alway's empty.
{{ dump(fields.field_myfieldname) }}
print object(stdClass)[1899] ...
{{ dump(fields.field_myfieldname.raw) }}
print 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" />
why is this so hard ?
回答1:
Instead of building stuff in the twig files, you should instead preprocess your data and then reference your new variable in your twig file.
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";
}
}
Then in your field--node--field-myfieldname.html.twig file, call your new variable
{{ customfield }}
If you are returning html, call your new variable like so
{{ customfield|raw }}
来源:https://stackoverflow.com/questions/35061025/acces-raw-data-in-drupal-8-view-template