public static void main(String[] args) { try { final DirectoryTemplateLoader loader = new DirectoryTemplateLoader(new File(".")); TemplateDocument templateDocument = loader.parseTemplate("kitchensink.html"); final TemplateFactory f = loader.newTemplateFactory("kitchensink.html"); Template template = f.createTemplate(); HashMap<Long, Member> members = new HashMap<Long, Member>(); members.put(1l, new Member(1l, "Member 1")); members.put(2l, new Member(2l, "Member 2")); members.put(3l, new Member(3l, "Member 3")); members.put(4l, new Member(4l, "Member 4")); Model model = new Model(members); Auth auth = new Auth(members.get(2l)); template.setProperty("model", model); template.setProperty("auth", auth); Writer writer = new OutputStreamWriter(System.out); template.printTo(writer); writer.flush(); System.out.flush(); } catch (TemplateLoadingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private String findEntity(String sentence) { System.out.println(sentence); Word word = bm.segment(sentence); List<String> words = word.getWords(); System.out.println(words.toString()); boolean isMap = true; for (Template template : templates) { String[] templateWords = template.getWords(); if (words.size() == templateWords.length) { isMap = true; for (int i = 0; i < words.size(); i++) { if (templateWords[i].equals("{entity}")) { entities.add(words.get(i)); } else { if (!words.get(i).equals(templateWords[i])) { entities = new ArrayList<>(); isMap = false; break; } } } if (isMap) return template.getSparql(); } } return null; }
private void render() { PerfTimer timer = PerfTimer.get(this, "render"); SafeHtmlBuilder builder = new SafeHtmlBuilder(); if (data != null) { for (Contact c : data) { builder.append( TEMPLATE.item( "", AppResources.INSTANCE.css().profilePic(), c.getPicURL(), AppResources.INSTANCE.css().detailBlock(), c.getName(), c.getEmail(), c.getPhone())); } } else { builder.append( TEMPLATE.loading( AppResources.INSTANCE.css().loading(), AppResources.INSTANCE.loadingImage().getURL(), Messages.INSTANCE.listLoading())); } getElement().setInnerHTML(builder.toSafeHtml().asString()); timer.end(); }
private boolean matchAuthority(Template input, Status status) { pickMatchingChildren(input.getUsername(), status); pickMatchingChildren(input.getPassword(), status); pickMatchingChildren(input.getHost(), status); pickMatchingChildren(input.getPort(), status); return status.hasCandidates(); }
@SuppressWarnings("nls") Object lookup(String key, Map<String, Object> args) { Object value = null; TemplateResource r = null; if (key.startsWith(":include:")) { key = key.substring(9); r = mTemplate.lookupResource(key); if (r != null) { value = r.mContent; } } else if (key.startsWith(":parse:")) { key = key.substring(7); r = mTemplate.lookupResource(key); /** Avoid recursion at this point */ if (r != null && r != this) { value = r.process(args); } } else { value = args.get(key); if (value == null) { value = mTemplate.mProperties.get(key); } } return value; }
@RequestMapping(value = "/edit-vote.jsp", method = RequestMethod.GET) public ModelAndView showForm(HttpServletRequest request, @RequestParam("msgid") int msgid) throws Exception { Template tmpl = Template.getTemplate(request); if (!tmpl.isModeratorSession()) { throw new AccessViolationException("Not authorized"); } Map<String, Object> params = new HashMap<String, Object>(); params.put("msgid", msgid); Connection db = null; try { db = LorDataSource.getConnection(); Poll poll = Poll.getPollByTopic(db, msgid); params.put("poll", poll); List<PollVariant> variants = poll.getPollVariants(db, Poll.ORDER_ID); params.put("variants", variants); return new ModelAndView("edit-vote", params); } finally { if (db != null) { db.close(); } } }
private void setViewTemplate0(Template config) { config.path("/"); config.engine(JspEngine.class); config.suffix(null); /** 一个用户用来自定义的hook */ setViewTemplate(config); }
@Test public void message_command_should_format_message_arguments() throws Exception { Template template = loader.load("attribute-message.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<p title=\"Subject subject 1 Date 2011-12-01\"></p>" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
@Test public void value_message_command_should_set_value_attribute() throws Exception { Template template = loader.load("value-message.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<input value=\"Subject subject 1 Date 2011-12-01\">" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
@Test public void should_escape_quote_in_attribute_value() throws Exception { Template template = loader.load("attribute-quote.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>\n" + " <p lang=\""\"></p>\n" + " <p lang=\"'\"></p>\n" + "</body>\n"; assertEquals(EXPECTED_OUTPUT, writer.toString()); }
@Test public void readonly_command_should_set_readonly_attribute() throws Exception { setVariable("exampleReadonly", "readonly"); Template template = loader.load("readonly.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<input readonly=\"readonly\">" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
@Test public void disabled_command_should_set_disabled_attribute() throws Exception { setVariable("exampleDisabled", "disabled"); Template template = loader.load("disabled.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<input disabled=\"disabled\">" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
private void update() { Vector<String> data = new Vector<String>(); Iterator<Template> i = templateMap.values().iterator(); while (i.hasNext()) { Template template = i.next(); data.add(template.getName()); } templateList.setListData(data); repaint(); }
@Test public void missing_value_should_remove_attribute() throws Exception { setVariable("greeting", "replace"); Template template = loader.load("attribute-multiple.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<p title=\"replace\">" + "</p>" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
@Test public void should_replace_existing_attribute() throws Exception { setVariable("languageCode", "replace"); Template template = loader.load("attribute-replace.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<p lang=\"replace\"></p>" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
@Test public void value_command_should_set_value_attribute() throws Exception { setVariable("greeting", "add"); Template template = loader.load("value.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<input value=\"add\">" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
@Test public void should_set_attribute_when_attribute_does_not_exist() throws Exception { setVariable("languageCode", "add"); Template template = loader.load("attribute-add.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<p lang=\"add\"></p>" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
@Test public void default_prefix_attribute_command_should_set_attribute() throws Exception { setVariable("languageCode", "add"); Template template = loader.load("default-prefix-attribute.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<p lang=\"add\"></p>" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
private Match createMatch( MatchSegment bestMatchSegment, PathNode bestPath, QueryNode bestQuery, Template input) { Match match = null; if (bestPath != null) { // && ( bestQuery != null || !bestPath.hasQueries() ) ) { if (bestQuery != null) { match = new Match(bestQuery.template, bestQuery.value); } else { match = new Match(bestPath.template, bestPath.value); } MatchParams matchParams = new MatchParams(); // Add the matching query segments to the end of the list. if (bestQuery != null) { Map<String, Query> inputQuery = input.getQuery(); for (Query templateSegment : bestQuery.template.getQuery().values()) { Query inputSegment = inputQuery.get(templateSegment.getQueryName()); if (inputSegment != null && templateSegment.matches(inputSegment)) { extractSegmentParams(templateSegment, inputSegment, matchParams); } } } // If the template has the "extra" query queryParam then collect query params that were // not already matched. if (bestQuery != null) { Query extra = bestQuery.template.getExtra(); if (extra != null) { String paramName = extra.getParamName(); if (paramName != null && paramName.length() > 0) { for (Query query : input.getQuery().values()) { String queryName = query.getQueryName(); if (matchParams.resolve(queryName) == null) { for (Segment.Value value : query.getValues()) { matchParams.addValue(queryName, value.getEffectivePattern()); } } } } } } // Walk back up the matching segment tree. MatchSegment matchSegment = bestMatchSegment; while (matchSegment != null && matchSegment.pathNode.depth > 0) { extractSegmentParams(matchSegment.templateSegment, matchSegment.inputSegment, matchParams); matchSegment = matchSegment.parentMatch; } match.params = matchParams; } return match; }
@Test public void toJSON() throws IOException { Handlebars handlebars = new Handlebars(); handlebars.registerHelper("@json", JSONHelper.INSTANCE); Template template = handlebars.compile("{{@json this}}"); CharSequence result = template.apply(new Blog("First Post", "...")); assertEquals("{\"title\":\"First Post\",\"body\":\"...\",\"comments\":[]}", result); }
@Test public void selected_command_should_set_selected_attribute() throws Exception { setVariable("exampleSelected", "selected"); Template template = loader.load("selected.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<select>" + "<option selected=\"selected\"></option>" + "</select>" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
public void deleteTemplate(Template t) { int idx = 0; for (int i = 0; i < mTemplates.size(); i++) { Template tx = mTemplates.get(i); if (t.getTitle().equals(tx.getTitle()) && t.getText().equals(tx.getText())) { idx = i; break; } } mTemplates.remove(idx); }
@Override public void execute(Template tmpl, Template.Context ctx, Writer out) { Object value = tmpl.getValue(ctx, _name, _line); if (value != null) { String text = String.valueOf(value); write(out, _stripSpan ? stripSpan(text) : text); return; } // field modifiers String[] parts = _name.split(":", 3); String mod = ""; String tag = ""; String extra = null; if (parts.length == 1 || parts[0].equals("")) { write(out, String.format("{unknown field %s}", _name)); return; } else if (parts.length == 2) { mod = parts[0]; tag = parts[1]; } else if (parts.length == 3) { mod = parts[0]; extra = parts[1]; tag = parts[2]; } value = tmpl.getValue(ctx, tag, _line); // built-in modifiers if (mod.equals("text")) { // strip html if (value != null) { write(out, stripSpan(String.valueOf(value))); } return; } else if (mod.equals("type")) { // type answer field; convert it to [[type:...]] for the gui code to process write(out, String.format("[[%s]]", _name)); return; } else if (mod.equals("cq") || mod.equals("ca")) { // cloze deletion if (value != null && extra != null) { write(out, clozeText(String.valueOf(value), extra, mod.substring(1, 2))); } return; } else { // TODO: hook-based field modifier if (value == null) { write(out, String.format("{unknown field %s}", _name)); return; } write(out, String.valueOf(value)); } }
@Test public void should_set_multiple_attributes() throws Exception { setVariable("languageCode", "add"); setVariable("greeting", "replace"); Template template = loader.load("attribute-multiple.html"); template.execute(data, writer); final String EXPECTED_OUTPUT = "<body>" + "<p lang=\"add\" title=\"replace\">" + "</p>" + "</body>"; assertEquals(EXPECTED_OUTPUT, body()); }
@Test public void testCallSiteReuse() { Template tmpl = Mustache.compiler().compile("{{foo}}"); Object ctx = new Object() { String getFoo() { return "bar"; } }; for (int ii = 0; ii < 50; ii++) { assertEquals("bar", tmpl.execute(ctx)); } }
/** * Returns the target reference to redirect to by automatically resolving URI template variables * found using the {@link Template} class using the request and response as data models. * * @param request The request to handle. * @param response The response to update. * @return The target reference to redirect to. */ protected Reference getTargetRef(Request request, Response response) { // Create the template Template rt = new Template(this.targetTemplate); rt.setLogger(getLogger()); // Return the formatted target URI if (new Reference(this.targetTemplate).isRelative()) { // Be sure to keep the resource's base reference. return new Reference(request.getResourceRef(), rt.format(request, response)); } return new Reference(rt.format(request, response)); }
public void pack(Packer pk, Object target) throws IOException { if (messagePackable) { if (target == null) { throw new MessageTypeException("target is null."); } ((MessagePackable) target).messagePack(pk); return; } Template tmpl = TemplateRegistry.tryLookup(lookupType); if (tmpl == this || tmpl == null) { throw new MessageTypeException("Template lookup fail: " + lookupType); } tmpl.pack(pk, target); }
public static void initialize(Template instance) { plugin = instance; LWCPlugin lwcPlugin = (LWCPlugin) plugin.getServer().getPluginManager().getPlugin("LWC"); if (lwcPlugin != null) { lwc = lwcPlugin.getLWC(); } lockette = (Lockette) plugin.getServer().getPluginManager().getPlugin("Lockette"); if (lwc != null && !TSettings.LowDetailMode) { TLogger.info("LWC version " + lwcPlugin.getDescription().getVersion() + " loaded."); } if (lockette != null && !TSettings.LowDetailMode) { TLogger.info("Lockette version " + lockette.getDescription().getVersion() + " loaded."); } }
/** Translate the stylesheet into JVM bytecodes. */ public void translate() { _className = getXSLTC().getClassName(); // Define a new class by extending TRANSLET_CLASS final ClassGenerator classGen = new ClassGenerator( _className, TRANSLET_CLASS, Constants.EMPTYSTRING, ACC_PUBLIC | ACC_SUPER, null, this); addDOMField(classGen); // Compile transform() to initialize parameters, globals & output // and run the transformation compileTransform(classGen); // Translate all non-template elements and filter out all templates final Enumeration elements = elements(); while (elements.hasMoreElements()) { Object element = elements.nextElement(); // xsl:template if (element instanceof Template) { // Separate templates by modes final Template template = (Template) element; // _templates.addElement(template); getMode(template.getModeName()).addTemplate(template); } // xsl:attribute-set else if (element instanceof AttributeSet) { ((AttributeSet) element).translate(classGen, null); } else if (element instanceof Output) { // save the element for later to pass to compileConstructor Output output = (Output) element; if (output.enabled()) _lastOutputElement = output; } else { // Global variables and parameters are handled elsewhere. // Other top-level non-template elements are ignored. Literal // elements outside of templates will never be output. } } checkOutputMethod(); processModes(); compileModes(classGen); compileStaticInitializer(classGen); compileConstructor(classGen, _lastOutputElement); if (!getParser().errorsFound()) { getXSLTC().dumpClass(classGen.getJavaClass()); } }
@Test(expected = HandlebarsException.class) public void jsonViewNotFound() throws IOException { Handlebars handlebars = new Handlebars(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(Feature.DEFAULT_VIEW_INCLUSION, false); handlebars.registerHelper("@json", new JSONHelper(mapper)); Template template = handlebars.compile("{{@json this view=\"missing.ViewClass\"}}"); CharSequence result = template.apply(new Blog("First Post", "...")); assertEquals("{\"title\":\"First Post\"}", result); }