Skip to content

How to get all the variables of a template #532

Closed

Description

@benjaminSe1

Hello Guys,

First of all, thank you for your incredible work here !

I am using this lib within an api and I want to implement a function which takes in argument the twig template and return the list of the variables needed to compile/render the twig.

I have been looking at the source code to find any way to achieve this, but so far I didn't find any solution.
Did someone already implemented this kind of function ?

Thank you.

Activity

  1. ericmorand commented on May 4, 2021

    @ericmorand
    Member

    Hi @benjaminSe1,

    I think your best bet would be to use the included Twig parser to get the nodes that your template is made of, and isolate the nodes that handle the variable assignment. It should be easy enough.

    You can start by looking at that project I wrote some time ago, that transpiles Twig template to PHTML templates. To achieve this, it uses Twing parser to walk through the nodes:

    https://github.com/NightlyCommit/twig-to-phtml

    The parts that may be of interest to you are:

    https://github.com/NightlyCommit/twig-to-phtml/blob/c70eb15f9279a16e4450b1c899d0b1a5736d5b24/src/lib/Transpiler.ts#L509

    https://github.com/NightlyCommit/twig-to-phtml/blob/c70eb15f9279a16e4450b1c899d0b1a5736d5b24/src/lib/Transpiler.ts#L205

    With Twing, the nodes that handle variables (both assignment ans output) are node instanceof TwingNodeExpressionName and TwingNodeExpressionAssignName.

    This should be a fun tool to write actually. Let me know how it goes.

  2. locked and limited conversation to collaborators on Nov 27, 2023
  3. converted this issue into a discussion #554 on Nov 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions