以下是您需要的 Handlebars.java 依赖信息及详细使用说明。

📦 Maven 依赖配置

在 Maven 项目的 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>com.github.jknack</groupId>
    <artifactId>handlebars</artifactId>
    <version>4.3.3</version> <!-- 建议使用最新稳定版 -->
</dependency>

如果您在 Spring Boot 项目中使用,可以考虑使用专门的 Starter:

<dependency>
    <groupId>pl.allegro.tech.boot</groupId>
    <artifactId>handlebars-spring-boot-starter</artifactId>
    <version>最新版本</version>
</dependency>

💡 核心概念与基础示例

Handlebars.java 是一个基于 Mustache 语法的模板引擎,其主要特点是逻辑与展示分离,有助于编写更清晰的视图代码。

下面是一个最基本的用法示例,演示如何将数据应用到模板中:

import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class BasicExample {
    public static void main(String[] args) throws IOException {
        // 1. 创建 Handlebars 实例
        Handlebars handlebars = new Handlebars();
        
        // 2. 准备模板字符串(通常来自 .hbs 文件,这里使用内联模板)
        String templateString = "Hello, {{name}}! You have {{count}} new messages.";
        
        // 3. 编译模板
        Template template = handlebars.compileInline(templateString);
        
        // 4. 准备数据模型
        Map<String, Object> data = new HashMap<>();
        data.put("name", "Alice");
        data.put("count", 5);
        
        // 5. 将数据应用于模板,生成最终文本
        String result = template.apply(data);
        System.out.println(result); 
        // 输出: Hello, Alice! You have 5 new messages.
    }
}

🔧 进阶功能示例

1. 使用自定义助手 (Helpers)

当内置功能不能满足需求时,可以创建自定义助手来处理复杂逻辑,例如日期格式化或条件判断。

下面的例子展示如何创建一个用于日期格式化的自定义助手:

import com.github.jknack.handlebars.Helper;
import com.github.jknack.handlebars.Options;
// ... 其他import

public class DateFormatHelper implements Helper<LocalDateTime> {
    @Override
    public CharSequence apply(LocalDateTime date, Options options) throws IOException {
        if (date == null) {
            return "";
        }
        // 从助手参数中获取日期格式模式,默认为 "yyyy-MM-dd HH:mm:ss"
        String pattern = options.param(0, "yyyy-MM-dd HH:mm:ss"); 
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return date.format(formatter);
    }
}

// 注册并使用自定义助手
public class HelperExample {
    public static void main(String[] args) throws IOException {
        Handlebars handlebars = new Handlebars();
        
        // 注册名为 "formatDate" 的助手
        handlebars.registerHelper("formatDate", new DateFormatHelper());
        
        // 在模板中使用自定义助手
        String templateString = "Current time: {{formatDate now \"yyyy-MM-dd\"}}";
        Template template = handlebars.compileInline(templateString);
        
        Map<String, Object> data = new HashMap<>();
        data.put("now", LocalDateTime.now());
        
        String result = template.apply(data);
        System.out.println(result); // 输出: Current time: 2023-10-26
    }
}
2. 条件判断与循环遍历

模板支持基本的逻辑控制结构,如条件判断和循环遍历。

// 假设模板内容如下 (例如保存在 src/main/resources/templates/user_profile.hbs)
String templateContent = 
"{{#if user.loggedIn}}" +
"    <h1>Welcome back, {{user.name}}!</h1>" +
"    <p>Your recent orders:</p>" +
"    <ul>" +
"    {{#each user.orders}}" +
"        <li>{{this.itemName}} - ${{this.price}}</li>" +
"    {{/each}}" +
"    </ul>" +
"{{else}}" +
"    <p>Please log in.</p>" +
"{{/if}}";

// Java 代码中应用数据
public class LogicExample {
    public static void main(String[] args) throws IOException {
        Handlebars handlebars = new Handlebars();
        // 假设从文件加载模板,这里使用 compile 方法
        Template template = handlebars.compile("templates/user_profile"); 
        
        // 构建一个嵌套的数据结构
        Map<String, Object> userData = new HashMap<>();
        Map<String, Object> user = new HashMap<>();
        user.put("name", "Bob");
        user.put("loggedIn", true);
        
        List<Map<String, Object>> orders = new ArrayList<>();
        Map<String, Object> order1 = new HashMap<>();
        order1.put("itemName", "Coffee Mug");
        order1.put("price", 15.99);
        orders.add(order1);
        // ... 添加更多订单
        user.put("orders", orders);
        userData.put("user", user);
        
        String result = template.apply(userData);
        System.out.println(result);
    }
}

💎 总结

Handlebars.java 通过简洁的语法和强大的扩展能力(如自定义助手),有效地将数据与展示分离。核心步骤是:创建 Handlebars 实例 -> 编译模板字符串或文件得到 Template 对象 -> 准备数据模型 -> 使用 apply 方法生成最终文本。对于更复杂的场景,可以探索块级助手模板继承 或与 Spring Framework 等 Web 框架的集成。

希望这些信息能帮助您顺利使用 Handlebars.java!如果您在特定使用场景中遇到问题,欢迎继续提问。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐