Razzie
Razzie

Reputation: 31222

play - add global variable to custom tag

I have a string (obtained dynamically through a server side request) that represents HTML. In this HTML, there is a custom play tag. For example:

<html><body><div>#{myTag /}</div></body></html>

Now, I want to pass a variable to this tag:

Template playTemplate = TemplateLoader.loadString(myHtml); // the HTML above
playTemplate.compile();

SomeObject myObject = SomeObject.find("name", "test").first();
Map<String,Object> args = new HashMap<String, Object>();
args.put("myObject", myObject);
String result = playTemplate.render(args);

And in my custom "myTag.tag", the code looks like this:

<p>
    Hello world: ${myObject.name}
</p>

But I get an error:

Exception raised was NullPointerException : Cannot get property 'name' on null object.

The object is not null. When I replace #{myTag /} with ${myObject.name} in the HTML string, everything works fine! How do I pass an object to a custom tag?

Upvotes: 0

Views: 483

Answers (1)

Gelin Luo
Gelin Luo

Reputation: 14373

Your template should be

<html><body><div>#{myTag obj: myObject/}</div></body></html>

And your tag should be

<p>Hello world: ${_obj.name}</p>

In essence, you need to explicitly pass render args from template to tag.

the Rythm template engine support implicit pass render args to tag however. It brings many other features not found in groovy template. Check the full demo at http://rythmengine.com

Upvotes: 1

Related Questions