handlebars.java icon indicating copy to clipboard operation
handlebars.java copied to clipboard

Improve context extensibility

Open bjoern42 opened this issue 3 years ago • 0 comments

Would it be possible to add an additional protected Context constructor to allow more flexible extensions?

package com.github.jknack.handlebars;
...
public class Context {
...
  protected Context(final Context context) {
    this.parent = context.parent;
    this.model = context.model;
    this.data = context.data;
    this.extendedContext = context.extendedContext;
    this.resolver = context.resolver;
  }
...
}

Background info / reason for request: We would like to implement an inversed lookup order context, similar to the PartialCtx but without the key.equals("this") check:

package com.github.jknack.handlebars;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * Lookup order: extendedContext.model -> context.model
 */
public class InversedLookupOrderContext extends Context {

	public InversedLookupOrderContext(final Context parent, final Object model) {
		super(model);
		this.extendedContext = new Context(new HashMap<>());
		this.extendedContext.resolver = parent.resolver;
		this.extendedContext.extendedContext = new Context(Collections.emptyMap());
		this.resolver = parent.resolver;
		this.parent = parent;
		this.data = parent.data;
	}

	@Override
	public Object get(List<PathExpression> path) {
		return Optional
				.ofNullable(this.extendedContext.get(path))
				.orElseGet(() -> super.get(path));
	}
}

For this we need to expose parent.resolver and parent.data, which is not possible with the current implementation.

bjoern42 avatar Jun 27 '23 13:06 bjoern42