I have a custom entity, with the template my-custom-entity--my-entity.html.twig.

How do I access the ID in the template? I can do this by implementing hook_preprocess_entity, but am wondering if the ID is already available in the template.

  • 1
    Did you try passing the entity object as a variable and then {{ entity_object_name.id() }}? – Kevin Aug 10 at 21:46
  • I had just passed the ID as a variable. I guess I could pass the whole object in case I need other properties from it. I was mainly asking if the ID or the entity object is already available to the templates natively. – John Aug 11 at 14:35

You can just add the full object to a twig variable, so

$vars['myentity'] = $my_entity;

and then access with

{{ myentity.id }}

A bit more elegant is to implement hook_theme:

 * Implements hook_theme().
function MODULENAME_theme() {
  return [
    'customentity' => [
      'render element' => 'elements',

and a preprocess function to expose it to twigs customentity and maybe content variables:

function template_preprocess_customentity(&$variables) {
  $variables['customentity'] = $variables['elements']['#node'];

  // Helpful $content variable for templates.
  $variables += ['content' => []];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
| improve this answer | |
  • I think that would need to be {{ myentity.id() }}. Thanks for the answer. I had done something similar to this. What I was really trying to figure out here is if the entity id is already exposed natively, but I am guessing it is not. – John Aug 11 at 14:33
  • No, it isn't. Except your using a content type ;) Sometimes a custom entity is not worth the effort .. especially when it comes to make it fieldable, translateable or revisionable. – rémy Aug 11 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.