Search code examples
javaantlrliquid

Liquid Template nested expression with special characters in the path


Let's say I have the following map:

{
  context: {
     'parent-name': { /* data */ },
     'parent-name/http': { /* data */ },
  }
  self: {
    id: 'parent-name'
  }
}

Now I want to reference the parent-name/http but itself as a variable. I wrote the following expression:

{{context[self.id/http]}}

Using the https://github.com/bkiers/Liqp Java SDK, this throws an error:

parser error "mismatched input '/' expecting {'.', NEq, '==', '>=', '>', '<=', '<', '[', ']', '?', 'contains', 'and', 'or'}" on line 1, index 24

How do I write such expression?


Solution

  • AFAIK, you can't do that in one go. You'll first have to create the key, by using | append: "/http", and then retrieve the value with this key:

    String json = "{\n" +
        "  \"context\": {\n" +
        "     \"parent-name\": \"mu\",\n" +
        "     \"parent-name/http\": \"foo\"\n" +
        "  }," +
        "  \"self\": {\n" +
        "    \"id\": \"parent-name\"\n" +
        "  }\n" +
        "}";
    
    Template t = Template.parse(
        "{% assign key = self.id | append: \"/http\" %}" +
        "{{context[key]}}");
    
    System.out.println(t.render(json));