Skip to content

Commit

Permalink
Merge pull request #127 from pmlopes/feature/relaxed-bind
Browse files Browse the repository at this point in the history
#122: Initial proposal for relaxed bind
  • Loading branch information
jjlauer committed Jan 7, 2020
2 parents eb829d8 + aeb0e0e commit a28218c
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
22 changes: 22 additions & 0 deletions README.md
Expand Up @@ -237,6 +237,28 @@ String rendered = Rocker.template("views/index.rocker.html")
The template path and arguments will be runtime-checked. Please note that each
bindable value must match the name and type declared in your template.

In case your bindable map may contain more values that than the required ones
a relaxed bind is available. The relaxed alternative will not fail rendering
if an attribute is extra to the required list. For example:

```
@args (String name)
Hello ${name}!
```

Will render in relaxed mode as:

```java
Map map = new HashMap();
map.put("name", "Joe");
map.put("age", 42);

Rocker.template("views/hello.rocker.html")
.relaxedBind(map)
.render();
// -> Hello Joe!
```

### Activate hot reloading

Support for hot reloading is added to your generated templates by default in
Expand Down
Expand Up @@ -41,6 +41,21 @@ public BindableRockerModel bind(Map<String,Object> values) {
}
return this;
}

public BindableRockerModel relaxedBind(Map<String,Object> values) {
try {
Method f = model.getClass().getMethod("getArgumentNames");
for (String k : (String[]) f.invoke(null)) {
if (!values.containsKey(k)) {
throw new TemplateBindException(templatePath, templateClassName, "Unable to set property '" + k + "'");
}
bind(k, values.get(k));
}
return this;
} catch (Exception e) {
throw new TemplateBindException(templatePath, model.getClass().getCanonicalName(), "Unable to read getArgumentNames static method from template");
}
}

public BindableRockerModel bind(String name, Object value) {
Method setter = null;
Expand Down
Expand Up @@ -22,6 +22,9 @@
import org.junit.Assert;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
*
* @author joelauer
Expand Down Expand Up @@ -49,7 +52,24 @@ public void templateWithBindableProperties() throws Exception {

Assert.assertEquals("Test\n1", out);
}


@Test
public void templateWithRelaxedBindableProperties() throws Exception {
BindableRockerModel template = Rocker.template("rocker/Args.rocker.html");

Map<String, Object> properties = new HashMap<String, Object>();
properties.put("s", "Test");
properties.put("i", 1);
// should not be considered
properties.put("non-existing", null);

template.relaxedBind(properties);

String out = template.render().toString().trim();

Assert.assertEquals("Test\n1", out);
}

@Test
public void templateWithArgumentsInlined() throws Exception {
BindableRockerModel template = Rocker.template("rocker/Args.rocker.html", "Test", 1);
Expand Down

0 comments on commit a28218c

Please sign in to comment.