I previously asked a question about hiding the prefix/suffix in fields template
here, now I want to understand how can I programmatically hide the prefix or suffix of numeric fields in nodes templates
only?
-
You cannot. The field template that renders those values has no access to context in which it is being rendered(ie. access parent(s)). The only solution is to use hook_form_alter in your theme and alter specific fields in specific form.– user21641Oct 1, 2017 at 17:18
2 Answers
On node level you can configure the content of prefix and suffix in the field settings and you can show/hide them for each view mode separately.
So you rarely need to override this programmatically and this is not easy, because the prefix and suffix is not added as extra render elements, but to the markup string of the formatted field value. So you need string manipulation to subtract the prefix and suffix again.
A simple solution could be to display the database value, and so bypassing the field template altogether, by using the node object:
{{ node.field_example.value }}
But then you lose all formatting options, not only prefix/suffix.
You could remove the prefix via
In case you need it for comments.
/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function mymodule_comment_view_alter(array &$build, CommentInterface $comment, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
if ($comment->getFieldName() === 'field_name') {
unset($build['#prefix']);
}
}