返回

Java:SpringBoot 整合 Pebble模板引擎渲染html

发布时间:2023-02-11 15:06:54 306
# html# java# spring# apache# github

Pebble模板引擎,和PHP中的Twig、Python中的Django/jinja2模板语法类似

文档

  • https://pebbletemplates.io/
  • Pebble Spring Boot Starter
  • https://github.com/PebbleTemplates/pebble
  • https://mvnrepository.com/artifact/io.pebbletemplates/pebble-spring-boot-starter

依赖


<dependency>
    <groupId>io.pebbletemplates</groupId>
    <artifactId>pebble-spring-boot-starter</artifactId>
    <version>3.1.6</version>
</dependency>

注意

官方文档给出的版本号对应

ArtifactId spring-boot version
pebble-legacy-spring-boot-starter 2.x.x
pebble-spring-boot-starter 3.x.x

可是,使用pebble-legacy-spring-boot-starter 压根就不好使

打开starter的依赖配置可以看到

pebble-spring-boot-starter-3.1.6


    2.7.3

pebble-spring-boot-starter-3.2.0


    17
    3.0.0

所以,spring-boot-2版本,还得使用pebble-spring-boot-starter-3.1.6,只是不用最新版

完整配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.7</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>io.pebbletemplates</groupId>
			<artifactId>pebble-spring-boot-starter</artifactId>
			<version>3.1.6</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
	</dependencies>

</project>


配置 application.properties

# 文件扩展名,默认 .pebble
pebble.suffix=.html

控制器

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("name", "Tom");
        return "index";
    }
}

模板文件 resources/templates/index.html

hello {{name}}!




输出效果 在这里插入图片描述

参考 spring boot 集成 Pebble,更优雅地输出变量

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
Java两大工具库:Commons和Guava(6) 2023-02-11 14:44:27