Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to retrieve the variables in a template #1039

Open
vricosti opened this issue Mar 29, 2023 · 2 comments
Open

How to retrieve the variables in a template #1039

vricosti opened this issue Mar 29, 2023 · 2 comments

Comments

@vricosti
Copy link

vricosti commented Mar 29, 2023

Hi,

Sorry to ask here but I cannot find any example showing how to retrieve all the variables inside a template...
For instance with the following template:

Hello {{ name }}!

{% if score > 80 %}
I'm happy to inform you that you did very well on today's {{ test_name }}.
{% else %}
I'm sorry to inform you that you did not do so well on today's {{ test_name }}.
{% endif %}
You reached {{ score }} out of {{ max_score }} points.

I want to (name, score, test_name, max_score)

Thanks

@olegbonar
Copy link

I would also be interested in that

@halfopen
Copy link

halfopen commented Dec 26, 2023


@Test
    public void jinjaTest() {
        String template = "Hello {{ name }}!\n" +
                "\n" +
                "{% if score > 80 %}\n" +
                "I'm happy to inform you that you did very well on today's {{ test_name }}.\n" +
                "{% else %}\n" +
                "I'm sorry to inform you that you did not do so well on today's {{ test_name }}.\n" +
                "{% endif %}\n" +
                "You reached {{ score }} out of {{ max_score }} points.";

        Jinjava jinjava = new Jinjava();
        Node node = jinjava.newInterpreter().parse(template);

        List<String> result = new ArrayList<>();
        helper(node, result);
        System.out.println(result);
    }

    void helper(Node node, List<String> result) {
        if (Objects.isNull(node)) {
            return;
        }
        if (node instanceof ExpressionNode) {
            Token token = node.getMaster();
            if (token instanceof ExpressionToken) {
                result.add(((ExpressionToken) token).getExpr());
            }

        }
        if (!CollectionUtils.isEmpty(node.getChildren())) {
            for (Node child: node.getChildren()) {
                helper(child, result);
            }
        }
    }

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants