Skip to content

Instantly share code, notes, and snippets.

@Laurian
Created September 14, 2017 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Laurian/db5ace2b56a516b71f01658fe50e83eb to your computer and use it in GitHub Desktop.
Save Laurian/db5ace2b56a516b71f01658fe50e83eb to your computer and use it in GitHub Desktop.
Handlebars.tag (JSP), `<h:handlebars template="example" context="${pageContext}" />`
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%@ tag import="java.util.*" %>
<%@ tag import="com.github.jknack.handlebars.io.TemplateLoader" %>
<%@ tag import="com.github.jknack.handlebars.io.ServletContextTemplateLoader" %>
<%@ tag import="com.github.jknack.handlebars.Handlebars" %>
<%@ tag import="com.github.jknack.handlebars.Template" %>
<%@ tag import="com.github.jknack.handlebars.Context" %>
<%@ attribute name="template" required="true" %>
<%@ attribute name="context" required="true" type="javax.servlet.jsp.PageContext" %>
<%
JspContext jspContext = getJspContext();
TemplateLoader loader = new ServletContextTemplateLoader(((PageContext) jspContext).getServletContext(), "/templates", ".template.html");
Handlebars handlebars = new Handlebars(loader);
try {
Template t = handlebars.compile(jspContext.getAttribute("template").toString());
Map map = new HashMap();
// request attrs
// Enumeration attrs = ((PageContext) jspContext).getRequest().getAttributeNames();
// current page context (just tag attrs)
// Enumeration attrs = jspContext.getAttributeNamesInScope(PageContext.PAGE_SCOPE);
// parent page context, passed via attr
PageContext parentContext = (PageContext) jspContext.getAttribute("context");
Enumeration attrs = parentContext.getAttributeNamesInScope(PageContext.PAGE_SCOPE);
while(attrs.hasMoreElements()) {
String name = attrs.nextElement().toString();
// req attrs
// map.put(name, ((PageContext) jspContext).getRequest().getAttribute(name));
// current page context
// map.put(name, jspContext.getAttribute(name));
// parent page context
// replicate attrs into current context too
map.put(name, parentContext.getAttribute(name));
jspContext.setAttribute(name, parentContext.getAttribute(name), PageContext.PAGE_SCOPE);
}
Context context = Context.newBuilder(map).build();
%><%= t.apply(context) %><%
// context.destroy();
} catch (Exception e) {
%><%= e %><%
}
%>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment