0

I am following the code snippet provided here

{# Link to frontpage view. #} <a href="{{ path('view.frontpage.page_1') }}">{{ 'View all content'|t }}</a>

{# Link to user entity/profile page. #} <a href="{{ path('entity.user.canonical', {'user': user.id}) }}">{{ 'View user profile'|t }}</a>

{# Link to node page. #} <a href="{{ path('entity.node.canonical', {'node': node.id}) }}">{{ 'View node page'|t }}</a>

https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates#path

As the function says path($name, $parameters, $options), I want to add a link which has query parameters as shown in below

blue?destination=blue-search&cookie[blue_referrer]=3622&cookie[blue_type]=node

I tried implementing it as follows

<a href="{{ 
               path('blue_general.blue',
               {'node': node.id}, 
               {'query': [
                 'destination': path('view.blue_search.page_1'),
                 'cookie[blue_referrer]': node.id,
                 'cookie[blue_type]':'node'
                 ] 
                }
               ) 
               }}">Find a Distributor</a>

but it gives an error

The website encountered an unexpected error. Please try again later.Twig_Error_Syntax: An array element must be followed by a comma. Unexpected token "punctuation" of value ":" ("punctuation" expected with value ","). in Twig_TokenStream->expect() (line 124 of /templates/node/node--product.html.twig). Twig_ExpressionParser->parseArrayExpression() (Line: 205)

  • Twig doesn't have associative arrays like PHP, you need to pass a hash (replace square brackets with curly ones) – Clive Apr 5 at 9:30
  • HI @Clive thanks, <a href="{{ path('blue_general.redirect', {'destination': path('view.blue_search.page_1'), 'cookie[blue_referrer]': node.id, 'cookie[blue_type]': node } ) }}">Find</a> I need to pass '[' but its passing %5 how can I make sure the query params has [ and not '[' ? – harshal Apr 5 at 9:39
  • 1
    You don’t want to do that - 100% guaranteed-valid urls don’t contain square brackets (RFC3986), they need to be escaped. The browser and server both know what to do with it so I wouldn’t worry – Clive Apr 5 at 9:41
  • Thanks buddy @Clive – harshal Apr 5 at 13:51
2

Twig uses hashes where PHP uses associative arrays. So to fix your code just convert the array syntax to a hash literal:

{{ 
  path('blue_general.blue',
    {'node': node.id}, 
    {'query': {
      'destination': path('view.blue_search.page_1'),
      'cookie[blue_referrer]': node.id,
      'cookie[blue_type]':'node'
    }}
  ) 
}}

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.