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

Allow expressions as custom tag parameters #70

Closed
smarter opened this issue Jan 17, 2018 · 1 comment
Closed

Allow expressions as custom tag parameters #70

smarter opened this issue Jan 17, 2018 · 1 comment

Comments

@smarter
Copy link

smarter commented Jan 17, 2018

In liqp 0.6 it was possible to use a custom tag foo like this:

{% foo a.b.c %}

But since #46 the parameter is always parsed as the string "a.b.c", and there seems to be no built-in way to parse and evaluate the expression in this string. The following does not work either (parsing fails with a NoViableAltException):

{% foo {{ a.b.c }} %}

Is there an alternative to this? The documentation generator of the next-gen Scala compiler currently relies on this: scala/scala3#3859

@bkiers
Copy link
Owner

bkiers commented Jan 17, 2018

Yeah, that is unfortunate that the specs say (all!) parameters provided to a custom tag are teated as a single string.

You could evaluate the parameter-string(s) as an expression in your custom tag. Perhaps a bit of a hack, but do-able:

import liqp.nodes.LNode;
import liqp.tags.Tag;

public class Test {

  public static void main(String[] args) {

    String source = "{% dummy a.b.c %}{{ a.b.c }}{% enddummy %}";

    String jsonVariables = "{ \"a\": { \"b\": { \"c\": 42 }}}";

    String rendered = Template
        .parse(source)
        .with(new Dummy())
        .render(jsonVariables);

    System.out.println(rendered);
  }
}

class Dummy extends Tag {

  Dummy() {
    super("dummy");
  }

  @Override
  public Object render(TemplateContext context, LNode... nodes) {

    String parameters = nodes[0].render(context).toString();

    Object evaluated = Template
        .parse(String.format("{{%s}}", parameters))
        .render(context.getVariables());

    System.out.println("parameters -> " + parameters);
    System.out.println("evaluated  -> " + evaluated);

    return null;
  }
}

will print:

parameters -> a.b.c
evaluated  -> 42

@bkiers bkiers closed this as completed Jan 24, 2018
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

2 participants