Get node ID or URL in Twig on field levelGet Image URL in TwigHow to get variables of field from a view in twig?How to get the valid URL of a Link field from within a Twig template?Twig field collection theme get field idHow to get the value / URL of a Link field in a Twig template?Theming link fields, getting URL valueTwig - accessing node propertiesGet the alt for the image on views twigHow to get node url from Entity Reference field?Twig get field value from panel page

How many bits in the resultant hash will change, if the x bits are changed in its the original input?

Is it ethical for a company to ask its employees to move furniture on a weekend?

How to have a continuous player experience in a setting that's likely to favor TPKs?

What is the word for "event executor"?

What prompted Cuba to fight against South African Imperialism?

Why does "git status" show I'm on the master branch and "git branch" does not?

Cover a cube with four-legged walky-squares!

What is the German word or phrase for "village returning to forest"?

Sending a photo of my bank account card to the future employer

Cauchy reals and Dedekind reals satisfy "the same mathematical theorems"

ArcPy Delete Function not working inside for loop?

Is it OK to use personal email ID for faculty job applications or should we use (current) institute's ID

If I stood next to a piece of metal heated to a million degrees, but in a perfect vacuum, would I feel hot?

Was Apollo 13 radio blackout on reentry longer than expected?

Is straight-up writing someone's opinions telling?

Do dragons smell of lilacs?

A verb to describe specific positioning of three layers

Is it okay for a chapter's POV to shift as it progresses?

Alternator dying so junk car?

Alphanumeric Line and Curve Counting

How to make a plagal cadence sound convincing as an ending?

What are the basics of commands in Minecraft Java Edition?

How to honestly answer questions from a girlfriend like "How did you find this place" without giving the impression I'm always talking about my exes?

How possible is a successful landing just with 1 wing?



Get node ID or URL in Twig on field level


Get Image URL in TwigHow to get variables of field from a view in twig?How to get the valid URL of a Link field from within a Twig template?Twig field collection theme get field idHow to get the value / URL of a Link field in a Twig template?Theming link fields, getting URL valueTwig - accessing node propertiesGet the alt for the image on views twigHow to get node url from Entity Reference field?Twig get field value from panel page






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have a field value, which I would like to link to the content (to the node itself, using it in a teaser).



How can I get the URL or at least the ID on field level, to create that link?










share|improve this question



















  • 1





    Do you mean the ID of the entity (node) that the field that's being rendered is attached to?

    – Clive
    8 hours ago

















2















I have a field value, which I would like to link to the content (to the node itself, using it in a teaser).



How can I get the URL or at least the ID on field level, to create that link?










share|improve this question



















  • 1





    Do you mean the ID of the entity (node) that the field that's being rendered is attached to?

    – Clive
    8 hours ago













2












2








2








I have a field value, which I would like to link to the content (to the node itself, using it in a teaser).



How can I get the URL or at least the ID on field level, to create that link?










share|improve this question
















I have a field value, which I would like to link to the content (to the node itself, using it in a teaser).



How can I get the URL or at least the ID on field level, to create that link?







theming






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 7 hours ago









leymannx

8,0995 gold badges35 silver badges67 bronze badges




8,0995 gold badges35 silver badges67 bronze badges










asked 8 hours ago









BenjaminBenjamin

326 bronze badges




326 bronze badges







  • 1





    Do you mean the ID of the entity (node) that the field that's being rendered is attached to?

    – Clive
    8 hours ago












  • 1





    Do you mean the ID of the entity (node) that the field that's being rendered is attached to?

    – Clive
    8 hours ago







1




1





Do you mean the ID of the entity (node) that the field that's being rendered is attached to?

– Clive
8 hours ago





Do you mean the ID of the entity (node) that the field that's being rendered is attached to?

– Clive
8 hours ago










3 Answers
3






active

oldest

votes


















2














The node in a field template is the parent entity you find in element['#object'], which you can use to build the path:



 path('entity.node.canonical', 'node': element['#object'].id) 





share|improve this answer























  • Would this also work if the same field is coincidentally used by another entity type (Paragraph) at the same time? Not sure if this is possible at all...

    – leymannx
    8 hours ago






  • 1





    You wouldn't put this code in a generic field.html.twig, but in a template name suggestion targeting a specific field. If you have the same field name in different entities you can still target the specific one by adding the entity type to the template name.

    – 4k4
    7 hours ago












  • Thanks to everybody for the super fast help!

    – Benjamin
    7 hours ago


















1














You should maybe preprocess you the URL in place. Via template_preprocess_field get the node ID, build the path alias, send it to Twig.



/**
* Implements template_preprocess_field__FIELD_NAME().
*/
function MYTHEME_preprocess_field__MYFIELD(&$variables)

if ($variables['element']['#entity_type'] === 'node')
$node = $variables['element']['#object'];
$nid = $node->id();
$variables['myurl'] = Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid);




In field.html.twig then do:



% if myurl %
<a href=" myurl ">Kool Keith</a>
% endif %





share|improve this answer























  • Is there any disadvantage (e.g. security) including the URL via element['#object'] without preprocessing (like suggested in the answers above)?

    – Benjamin
    7 hours ago











  • @Benjamin – That's what I asked under @4k4's answer. I guess fields can be shared across entities (but not sure about that), then an additional check for node would be nice. But from a security point of view there's no difference.

    – leymannx
    7 hours ago


















1














Without preprocessing, directly in Twig:



# get owner entity #
% set owner_entity = element['#object'] %
# render id #
id = element['#object'].id
# render raw field value #
field foo = element['#object'].field_foo.0.value





share|improve this answer

























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "220"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdrupal.stackexchange.com%2fquestions%2f283569%2fget-node-id-or-url-in-twig-on-field-level%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    The node in a field template is the parent entity you find in element['#object'], which you can use to build the path:



     path('entity.node.canonical', 'node': element['#object'].id) 





    share|improve this answer























    • Would this also work if the same field is coincidentally used by another entity type (Paragraph) at the same time? Not sure if this is possible at all...

      – leymannx
      8 hours ago






    • 1





      You wouldn't put this code in a generic field.html.twig, but in a template name suggestion targeting a specific field. If you have the same field name in different entities you can still target the specific one by adding the entity type to the template name.

      – 4k4
      7 hours ago












    • Thanks to everybody for the super fast help!

      – Benjamin
      7 hours ago















    2














    The node in a field template is the parent entity you find in element['#object'], which you can use to build the path:



     path('entity.node.canonical', 'node': element['#object'].id) 





    share|improve this answer























    • Would this also work if the same field is coincidentally used by another entity type (Paragraph) at the same time? Not sure if this is possible at all...

      – leymannx
      8 hours ago






    • 1





      You wouldn't put this code in a generic field.html.twig, but in a template name suggestion targeting a specific field. If you have the same field name in different entities you can still target the specific one by adding the entity type to the template name.

      – 4k4
      7 hours ago












    • Thanks to everybody for the super fast help!

      – Benjamin
      7 hours ago













    2












    2








    2







    The node in a field template is the parent entity you find in element['#object'], which you can use to build the path:



     path('entity.node.canonical', 'node': element['#object'].id) 





    share|improve this answer













    The node in a field template is the parent entity you find in element['#object'], which you can use to build the path:



     path('entity.node.canonical', 'node': element['#object'].id) 






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 8 hours ago









    4k44k4

    56k5 gold badges71 silver badges114 bronze badges




    56k5 gold badges71 silver badges114 bronze badges












    • Would this also work if the same field is coincidentally used by another entity type (Paragraph) at the same time? Not sure if this is possible at all...

      – leymannx
      8 hours ago






    • 1





      You wouldn't put this code in a generic field.html.twig, but in a template name suggestion targeting a specific field. If you have the same field name in different entities you can still target the specific one by adding the entity type to the template name.

      – 4k4
      7 hours ago












    • Thanks to everybody for the super fast help!

      – Benjamin
      7 hours ago

















    • Would this also work if the same field is coincidentally used by another entity type (Paragraph) at the same time? Not sure if this is possible at all...

      – leymannx
      8 hours ago






    • 1





      You wouldn't put this code in a generic field.html.twig, but in a template name suggestion targeting a specific field. If you have the same field name in different entities you can still target the specific one by adding the entity type to the template name.

      – 4k4
      7 hours ago












    • Thanks to everybody for the super fast help!

      – Benjamin
      7 hours ago
















    Would this also work if the same field is coincidentally used by another entity type (Paragraph) at the same time? Not sure if this is possible at all...

    – leymannx
    8 hours ago





    Would this also work if the same field is coincidentally used by another entity type (Paragraph) at the same time? Not sure if this is possible at all...

    – leymannx
    8 hours ago




    1




    1





    You wouldn't put this code in a generic field.html.twig, but in a template name suggestion targeting a specific field. If you have the same field name in different entities you can still target the specific one by adding the entity type to the template name.

    – 4k4
    7 hours ago






    You wouldn't put this code in a generic field.html.twig, but in a template name suggestion targeting a specific field. If you have the same field name in different entities you can still target the specific one by adding the entity type to the template name.

    – 4k4
    7 hours ago














    Thanks to everybody for the super fast help!

    – Benjamin
    7 hours ago





    Thanks to everybody for the super fast help!

    – Benjamin
    7 hours ago













    1














    You should maybe preprocess you the URL in place. Via template_preprocess_field get the node ID, build the path alias, send it to Twig.



    /**
    * Implements template_preprocess_field__FIELD_NAME().
    */
    function MYTHEME_preprocess_field__MYFIELD(&$variables)

    if ($variables['element']['#entity_type'] === 'node')
    $node = $variables['element']['#object'];
    $nid = $node->id();
    $variables['myurl'] = Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid);




    In field.html.twig then do:



    % if myurl %
    <a href=" myurl ">Kool Keith</a>
    % endif %





    share|improve this answer























    • Is there any disadvantage (e.g. security) including the URL via element['#object'] without preprocessing (like suggested in the answers above)?

      – Benjamin
      7 hours ago











    • @Benjamin – That's what I asked under @4k4's answer. I guess fields can be shared across entities (but not sure about that), then an additional check for node would be nice. But from a security point of view there's no difference.

      – leymannx
      7 hours ago















    1














    You should maybe preprocess you the URL in place. Via template_preprocess_field get the node ID, build the path alias, send it to Twig.



    /**
    * Implements template_preprocess_field__FIELD_NAME().
    */
    function MYTHEME_preprocess_field__MYFIELD(&$variables)

    if ($variables['element']['#entity_type'] === 'node')
    $node = $variables['element']['#object'];
    $nid = $node->id();
    $variables['myurl'] = Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid);




    In field.html.twig then do:



    % if myurl %
    <a href=" myurl ">Kool Keith</a>
    % endif %





    share|improve this answer























    • Is there any disadvantage (e.g. security) including the URL via element['#object'] without preprocessing (like suggested in the answers above)?

      – Benjamin
      7 hours ago











    • @Benjamin – That's what I asked under @4k4's answer. I guess fields can be shared across entities (but not sure about that), then an additional check for node would be nice. But from a security point of view there's no difference.

      – leymannx
      7 hours ago













    1












    1








    1







    You should maybe preprocess you the URL in place. Via template_preprocess_field get the node ID, build the path alias, send it to Twig.



    /**
    * Implements template_preprocess_field__FIELD_NAME().
    */
    function MYTHEME_preprocess_field__MYFIELD(&$variables)

    if ($variables['element']['#entity_type'] === 'node')
    $node = $variables['element']['#object'];
    $nid = $node->id();
    $variables['myurl'] = Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid);




    In field.html.twig then do:



    % if myurl %
    <a href=" myurl ">Kool Keith</a>
    % endif %





    share|improve this answer













    You should maybe preprocess you the URL in place. Via template_preprocess_field get the node ID, build the path alias, send it to Twig.



    /**
    * Implements template_preprocess_field__FIELD_NAME().
    */
    function MYTHEME_preprocess_field__MYFIELD(&$variables)

    if ($variables['element']['#entity_type'] === 'node')
    $node = $variables['element']['#object'];
    $nid = $node->id();
    $variables['myurl'] = Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid);




    In field.html.twig then do:



    % if myurl %
    <a href=" myurl ">Kool Keith</a>
    % endif %






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 8 hours ago









    leymannxleymannx

    8,0995 gold badges35 silver badges67 bronze badges




    8,0995 gold badges35 silver badges67 bronze badges












    • Is there any disadvantage (e.g. security) including the URL via element['#object'] without preprocessing (like suggested in the answers above)?

      – Benjamin
      7 hours ago











    • @Benjamin – That's what I asked under @4k4's answer. I guess fields can be shared across entities (but not sure about that), then an additional check for node would be nice. But from a security point of view there's no difference.

      – leymannx
      7 hours ago

















    • Is there any disadvantage (e.g. security) including the URL via element['#object'] without preprocessing (like suggested in the answers above)?

      – Benjamin
      7 hours ago











    • @Benjamin – That's what I asked under @4k4's answer. I guess fields can be shared across entities (but not sure about that), then an additional check for node would be nice. But from a security point of view there's no difference.

      – leymannx
      7 hours ago
















    Is there any disadvantage (e.g. security) including the URL via element['#object'] without preprocessing (like suggested in the answers above)?

    – Benjamin
    7 hours ago





    Is there any disadvantage (e.g. security) including the URL via element['#object'] without preprocessing (like suggested in the answers above)?

    – Benjamin
    7 hours ago













    @Benjamin – That's what I asked under @4k4's answer. I guess fields can be shared across entities (but not sure about that), then an additional check for node would be nice. But from a security point of view there's no difference.

    – leymannx
    7 hours ago





    @Benjamin – That's what I asked under @4k4's answer. I guess fields can be shared across entities (but not sure about that), then an additional check for node would be nice. But from a security point of view there's no difference.

    – leymannx
    7 hours ago











    1














    Without preprocessing, directly in Twig:



    # get owner entity #
    % set owner_entity = element['#object'] %
    # render id #
    id = element['#object'].id
    # render raw field value #
    field foo = element['#object'].field_foo.0.value





    share|improve this answer



























      1














      Without preprocessing, directly in Twig:



      # get owner entity #
      % set owner_entity = element['#object'] %
      # render id #
      id = element['#object'].id
      # render raw field value #
      field foo = element['#object'].field_foo.0.value





      share|improve this answer

























        1












        1








        1







        Without preprocessing, directly in Twig:



        # get owner entity #
        % set owner_entity = element['#object'] %
        # render id #
        id = element['#object'].id
        # render raw field value #
        field foo = element['#object'].field_foo.0.value





        share|improve this answer













        Without preprocessing, directly in Twig:



        # get owner entity #
        % set owner_entity = element['#object'] %
        # render id #
        id = element['#object'].id
        # render raw field value #
        field foo = element['#object'].field_foo.0.value






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 8 hours ago









        HudriHudri

        2,2851 gold badge7 silver badges24 bronze badges




        2,2851 gold badge7 silver badges24 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Drupal Answers!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdrupal.stackexchange.com%2fquestions%2f283569%2fget-node-id-or-url-in-twig-on-field-level%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

            Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

            François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480