• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

jknack/handlebars.java: Logic-less and semantic Mustache templates with Java

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

jknack/handlebars.java

开源软件地址:

https://github.com/jknack/handlebars.java

开源编程语言:

Java 74.8%

开源软件介绍:

Become a Patreon Maven Central javadoc

Handlebars.java

Logic-less and semantic Mustache templates with Java

Handlebars handlebars = new Handlebars();

Template template = handlebars.compileInline("Hello {{this}}!");

System.out.println(template.apply("Handlebars.java"));

Output:

Hello Handlebars.java!

Handlebars.java is a Java port of handlebars.

Handlebars provides the power necessary to let you build semantic templates effectively with no frustration.

Mustache templates are compatible with Handlebars, so you can take a Mustache template, import it into Handlebars, and start taking advantage of the extra Handlebars features.

Requirements

  • Handlebars 4.3+ requires Java 8 or higher.

Getting Started

In general, the syntax of Handlebars templates is a superset of Mustache templates. For basic syntax, check out the Mustache manpage.

The Handlebars.java blog is a good place for getting started too. Javadoc is available at javadoc.io.

Maven

Stable version: Maven Central

  <dependency>
    <groupId>com.github.jknack</groupId>
    <artifactId>handlebars</artifactId>
    <version>${handlebars-version}</version>
  </dependency>

Loading templates

Templates are loaded using the TemplateLoader class. Handlebars.java provides three implementations of a TemplateLoader:

  • ClassPathTemplateLoader (default)
  • FileTemplateLoader
  • SpringTemplateLoader (see the handlebars-springmvc module)

This example loads mytemplate.hbs from the root of the classpath:

mytemplate.hbs:

Hello {{this}}!
Handlebars handlebars = new Handlebars();

Template template = handlebars.compile("mytemplate");

System.out.println(template.apply("Handlebars.java"));

Output:

Hello Handlebars.java!

You can specify a different TemplateLoader by:

TemplateLoader loader = ...;
Handlebars handlebars = new Handlebars(loader);

Templates prefix and suffix

A TemplateLoader provides two important properties:

  • prefix: useful for setting a default prefix where templates are stored.
  • suffix: useful for setting a default suffix or file extension for your templates. Default is: .hbs

Example:

TemplateLoader loader = new ClassPathTemplateLoader();
loader.setPrefix("/templates");
loader.setSuffix(".html");
Handlebars handlebars = new Handlebars(loader);

Template template = handlebars.compile("mytemplate");

System.out.println(template.apply("Handlebars.java"));

Handlebars.java will resolve mytemplate to /templates/mytemplate.html and load it.

The Handlebars.java Server

The handlebars.java server is small application where you can write Mustache/Handlebars template and merge them with data.

It is a useful tool for Web Designers.

Download from Maven Central:

  1. Go here
  2. Under the Download section click on jar

Maven:

<dependency>
  <groupId>com.github.jknack</groupId>
  <artifactId>handlebars-proto</artifactId>
  <version>${current-version}</version>
</dependency>

Usage: java -jar handlebars-proto-${current-version}.jar -dir myTemplates

Example:

myTemplates/home.hbs

<ul>
 {{#items}}
 {{name}}
 {{/items}}
</ul>

myTemplates/home.json

{
  "items": [
    {
      "name": "Handlebars.java rocks!"
    }
  ]
}

or if you prefer YAML myTemplates/home.yml:

items:
  - name: Handlebars.java rocks!

Open a browser a type:

http://localhost:6780/home.hbs

enjoy it!

Additional options:

  • -dir: set the template directory
  • -prefix: set the template's prefix, default is /
  • -suffix: set the template's suffix, default is .hbs
  • -context: set the context's path, default is /
  • -port: set port number, default is 6780
  • -content-type: set the content-type header, default is text/html

Multiple data sources per template

Sometimes you need or want to test multiple datasets over a single template, you can do that by setting a data parameter in the request URI.

Example:

http://localhost:6780/home.hbs?data=mytestdata

Please note you don't have to specify the extension file.

Helpers

Built-in helpers:

  • with
  • each
  • if
  • unless
  • log
  • block
  • partial
  • precompile
  • embedded
  • i18n and i18nJs
  • string helpers
  • conditional helpers

with, each, if, unless:

See the built-in helper documentation.

block and partial

Block and partial helpers work together to provide you Template Inheritance.

Usage:

  {{#block "title"}}
    ...
  {{/block}}

context: A string literal which defines the region's name.

Usage:

  {{#partial "title"}}
    ...
  {{/partial}}

context: A string literal which defines the region's name.

precompile

Precompile a Handlebars.java template to JavaScript using handlebars.js

user.hbs

Hello {{this}}!

home.hbs

<script type="text/javascript">
{{precompile "user"}}
</script>

Output:

<script type="text/javascript">
(function() {
  var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['user'] = template(function (Handlebars,depth0,helpers,partials,data) {
  helpers = helpers || Handlebars.helpers;
  var buffer = "", functionType="function", escapeExpression=this.escapeExpression;


  buffer += "Hi ";
  depth0 = typeof depth0 === functionType ? depth0() : depth0;
  buffer += escapeExpression(depth0) + "!";
  return buffer;});
})();
</script>

You can access the precompiled template with:

var template = Handlebars.templates['user']

By default it uses: /handlebars-v1.3.0.js to compile the template. Since handlebars.java 2.x it is also possible to use handlebars.js 2.x

Handlebars handlebars = new Handlebars();
handlebars.handlebarsJsFile("/handlebars-v2.0.0.js");

For more information have a look at the Precompiling Templates documentation.

Usage:

{{precompile "template" [wrapper="anonymous, amd or none"]}}

context: A template name. Required.

wrapper: One of "anonymous", "amd" or "none". Default is: "anonymous"

There is a maven plugin available too.

embedded

The embedded helper allow you to "embedded" a handlebars template inside a <script> HTML tag:

user.hbs

<tr>
  <td>{{firstName}}</td>
  <td>{{lastName}}</td>
</tr>

home.hbs

<html>
...
{{embedded "user"}}
...
</html>

Output:

<html>
...
<script id="user-hbs" type="text/x-handlebars">
<tr>
  <td>{{firstName}}</td>
  <td>{{lastName}}</td>
</tr>
</script>
...
</html>

Usage:

{{embedded "template"}}

context: A template name. Required.

i18n

A helper built on top of a {@link ResourceBundle}. A {@link ResourceBundle} is the most well known mechanism for internationalization (i18n) in Java.

Usage:

{{i18n "hello"}}

This require a messages.properties in the root of classpath.

Using a locale:

{{i18n "hello" locale="es_AR"}}

This requires a messages_es_AR.properties in the root of classpath.

Using a different bundle:

{{i18n "hello" bundle="myMessages"}}

This requires a myMessages.properties in the root of classpath.

Using a message format:

{{i18n "hello" "Handlebars.java"}}

Where hello is Hola {0}!, results in Hola Handlebars.java!.

i18nJs

Translate a ResourceBundle into JavaScript code. The generated code assumes you have the I18n in your application.

Usage:

{{i18nJs [locale] [bundle=messages]}}

If the locale argument is present it will translate that locale to JavaScript. Otherwise, it will use the default locale.

The generated code looks like this:

<script type="text/javascript">
  I18n.defaultLocale = 'es_AR';
  I18n.locale = 'es_AR';
  I18n.translations = I18n.translations || {};
  // Spanish (Argentina)
  I18n.translations['es_AR'] = {
    "hello": "Hi {{arg0}}!"
  }
</script>

Finally, it converts message patterns like: Hi {0} into Hi {{arg0}}. This make possible for the I18n JS library to interpolate variables.

string helpers

Functions like abbreviate, capitalize, join, dateFormat, yesno, etc., are available from StringHelpers.

NOTE: You need to register string helpers (they are not added by default)

conditional helpers

Functions like eq, neq, lt, gt, and, or, not, etc., are available from ConditionalHelpers.

NOTE: You need to register conditional helpers (they are not added by default)

TypeSafe Templates

TypeSafe templates are created by extending the TypeSafeTemplate interface. For example:

// 1
public static interface UserTemplate extends TypeSafeTemplate<User> {

  // 2
  public UserTemplate setAge(int age);

  public UserTemplate setRole(String role);

}

// 3
UserTemplate userTmpl = handlebars.compileInline("{{name}} is {{age}} years old!")
  .as(UserTemplate.class);

userTmpl.setAge(32);

assertEquals("Edgar is 32 years old!", userTmpl.apply(new User("Edgar")));
  1. You extend the TypeSafeTemplate interface.
  2. You add all the set method you need. The set method can returns void or TypeSafeTemplate object.
  3. You create a new type safe template using the: as() method.

Registering Helpers

There are two ways of registering helpers.

Using the Helper interface

handlebars.registerHelper("blog", new Helper<Blog>() {
  public CharSequence apply(Blog blog, Options options) {
    return options.fn(blog);
  }
});
handlebars.registerHelper("blog-list", new Helper<List<Blog>>() {
  public CharSequence apply(List<Blog> list, Options options) {
    String ret = "<ul>";
    for (Blog blog: list) {
      ret += "<li>" + options.fn(blog) + "</li>";
    }
    return new Handlebars.SafeString(ret + "</ul>");
  }
});

Using a HelperSource

A helper source is any class with public methods returning an instance of a CharSequence.

  public static? CharSequence methodName(context?, parameter*, options?) {
  }

Where:

  • A method can/can't be static
  • The method's name becomes the helper's name
  • Context, parameters and options are all optionals
  • If context and options are present they must be the first and last arguments of the method

All these are valid definitions of helper methods:

public class HelperSource {
  public String blog(Blog blog, Options options) {
    return options.fn(blog);
  }

  public static String now() {
    return new Date().toString();
  }

  public String render(Blog context, String param0, int param1, boolean param2, Options options) {
    return ...
  }
}

...

handlebars.registerHelpers(new HelperSource());

Or, if you prefer static methods only:

handlebars.registerHelpers(HelperSource.class);

With plain JavaScript

That's right since 1.1.0 you can write helpers in JavaScript:

helpers.js:

Handlebars.registerHelper('hello', function (context) {
 return 'Hello ' + context;
})
handlebars.registerHelpers(new File("helpers.js"));

Cool, isn't?

Helper Options

Parameters

handlebars.registerHelper("blog-list", new Helper<Blog>() {
  public CharSequence apply(List<Blog> list, Options options) {
    String p0 = options.param(0);
    assertEquals("param0", p0);
    Integer p1 = options.param(1);
    assertEquals(123, p1);
    ...
  }
});

Bean bean = new Bean();
bean.setParam1(123);

Template template = handlebars.compileInline("{{#blog-list blogs \"param0\" param1}}{{/blog-list}}");
template.apply(bean);

Default parameters

handlebars.registerHelper("blog-list", new Helper<Blog>() {
  public CharSequence apply(List<Blog> list, Options options) {
    String p0 = options.param(0, "param0");
    assertEquals("param0", p0);
    Integer p1 = options.param(1, 123);
    assertEquals(123, p1);
    ...
  }
});

Template template = handlebars.compileInline("{{#blog-list blogs}}{{/blog-list}}");

Hash


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
matyb/java-koans: A framework and lessons to learn java syntax and idioms in a l ...发布时间:2022-06-23
下一篇:
fdanismaz/java发布时间:2022-06-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap