The goal of the value module is to make field values easily accessible inside Twig templates.
$variables['_article'] = [
'nid' => 1,
'title' => 'Minus veritatis rem tenetur hic repellendus fugit.',
'created' => 1538956800,
'field_foo' => 'bar',
'field_author' => [
'uid' => 1,
'name' => 'john',
'field_company' => 'ACME Inc',
'field_picture' => [
'uri' => 'public://profiles/john.jpg',
'url' => 'https://example.com/sites/default/files/profiles/john.jpg',
'alt' => 'Tempora magni blanditiis maxime inventore.',
],
],
'field_categories' => [
[
'tid' => 1,
'name' => 'Lipsum',
'description' => 'Quod id aspernatur laboriosam fugiat totam.'
],
],
];
Examples
- Text fields:
{{ _article.title }}
- Text with summary:
{{ _artile.body.value }}
or{{ artile.body.summary }}
for the summary. - Link:
{{ _article.field_link.url }}
- Image:
<img src="{{ _article.field_image.url }} alt="{{ _article.field_image.alt }}" />
- Reference:
{{ value(_article.field_author).field_name }}
- And more...
Filters
The value module also ships with some helpful Twig filters.
- Image style:
{{ _article.field_image.uri|image_style('thumbnail') }}
- Markup:
{{ _article.body|markup }}
for rendering safe HTML markup. - Truncate:
{{ _article.title|truncate(10) }}
will truncate title to 10 characters. - Words:
{{ _article.title|words(5) }}
will truncate title to 5 words. - Pick:
{{ _article|pick(['field_name', 'field_author']) }}
to pick some values only. - Where:
{{ _array|where('foo') }}
will return an array with foo values only or{{ _ages|where(12, '>') }}
will return an array where ages are greater than 12.. - Rename keys:
{{ _article|rename_keys(field_title: 'title') }}
to rename keys.
See an example for |pick
and |rename_keys
here.
Important changes in the 8.x-2.x branch
1. The 8.x-2.x release for the value module changes how entity reference fields are serialized. This is now opt-in instead of being done automatically for you.
The EntityReferenceFieldItemNormalizer
now returns simple values for target_id, target_type..etc
which you can now feed to a Twig value()
function to get field values back.
Example: (assumes an article node type referencing an author entity type).
Before (8.x-1.x)
{{ _article.field_author.field_job_title }}
After (8.x-2.x)
{{ value(_article.field_author).field_job_title }}
2. id
has been renamed to target_id
Project information
- Module categories: Developer Tools
- 140 sites report using this module
- Created by shadcn on , updated
- Stable releases for this project are covered by the security advisory policy.
There are currently no supported stable releases.