Hello Fremarker!

FreeMarker шаблоны

Apache FreeMarker — это механизм шаблонов: библиотека Java для генерации текстового вывода (HTML-страницы, xml, файлы конфигурации, исходный код и.т.д. На вход подается шаблон, например html в котором есть специальные выражения, подготавливаются данные соответствующие этим выражением, а Freemarker динамически вставляет эти данные и получается динамически заполненный документ.

image

В статье FreeMarker
Spring boot
Macros
REST API

Т.е. простое выражение на freemarker это например $, в выражения поддерживаются вычисления, операции сравнения, условия, циклы, списки, встроенные функции, макрос и много др. Пример html с выражением $ (шаблон test.ftl):

Если теперь создать в java модель данных:

import freemarker.template.Configuration; import freemarker.template.Template; . // Конфигурация Configuration cfg = new Configuration(Configuration.VERSION_2_3_27); // модель данных Map root = new HashMap<>(); root.put("name", "Freemarker"); // шаблон Template temp = cfg.getTemplate("test.ftl"); // обработка шаблона и модели данных Writer out = new OutputStreamWriter(System.out); // вывод в консоль temp.process(root, out); 

то получим html документ с заполненным name.

Если надо обработать список, то используется конструкция #list, например для html списка:

В java, в модель данных подать список можно так

Map root = new HashMap<>(); . root.put("father", Arrays.asList("Alexander", "Petrov", 47));

Перейдем к Spring

В Spring boot есть поддержка Freemarker. На сайте SPRING INITIALIZR можно получить pom файл проекта.

  4.0.0 com.example demoFreeMarker 0.0.1-SNAPSHOT jar demoFreeMarker Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.0.4.RELEASE  UTF-8 UTF-8 1.8   org.springframework.boot spring-boot-starter-freemarker  org.springframework.boot spring-boot-devtools runtime  org.springframework.boot spring-boot-starter-test test     org.springframework.boot spring-boot-maven-plugin     
@SpringBootApplication public class DemoFreeMarkerApplication < public static void main(String[] args) < SpringApplication.run(DemoFreeMarkerApplication.class, args); >> 

В Spring есть уже подготовленный компонент конфигурации Configuration для freemarker. Для примера консольного приложения возьму spring интерфейс для обработки командной строки(CommandLineRunner) и подготовлю модель данных для следующего шаблона ftl (hello_test.ftl):

Java код для модели данных шаблона hello_test.ftl:

@Component public class CommandLine implements CommandLineRunner < @Autowired private Configuration configuration; public void run(String. args) < Maproot = new HashMap<>(); // для $ root.put("name", "Fremarker"); // для persons = new ArrayList<>(); persons.add(Arrays.asList("Alexander", "Petrov", 47)); persons.add(Arrays.asList("Slava", "Petrov", 13)); root.put("persons", persons); try < Template template = configuration.getTemplate("hello_test.ftl"); Writer out = new OutputStreamWriter(System.out); try < template.process(root, out); >catch (TemplateException e) < e.printStackTrace(); >> catch (IOException e) < e.printStackTrace(); >> > 

После обработки получим html документ:

        
Alexander Petrov 47
Slava Petrov 13

Макросы

В freemarker есть поддержка макросов, это очень удобная и сильная его сторона и использовать ее просто необходимо.

Это макрос с именем textInput и параметрами id (он обязательный) и value (он не обязательный, т.к. имеет значение по умолчанию). Далее идет его тело и использование входных параметров. В шаблоне файл с макросами подключается так:

Из шаблона макрос вызывается так:

Где ui это алиас который указали при подключении, $ переменная в модели, далее через алиас ссылаемся на имя макроса textInput и указываем его параметры, как минимум обязательные. Подготовлю простые макросы для html Input и Table:

$ это встроенная поддержка индекса элемента списка, подобных встроенных функций много. Если теперь изменить предыдущий основной шаблон и заменить в нем input и table на макросы, то получится такой документ:

REST

Конечно такую модель удобно использовать в web приложении. Подключаю зависимость в pom:

  org.springframework.boot spring-boot-starter-web  
@Controller public class DemoController < @Autowired private RepositoryService repositoryService; @GetMapping("/") public String index() < return "persons"; >@RequestMapping(value = "/search", method = RequestMethod.POST) public String hello(Model model, @RequestParam(defaultValue = "") String searchName) < List> persons = repositoryService.getRepository(); List> filterList = persons.stream() .filter(p -> p.get(0).contains(searchName)) .collect(Collectors.toList()); model.addAttribute("persons", filterList); model.addAttribute("lastSearch", searchName); return "persons"; > @RequestMapping(value = "/save", method = RequestMethod.POST) public String save(Model model, @ModelAttribute("person") Person person) < List> persons = repositoryService.addPerson(person); model.addAttribute("persons", persons); return "persons"; > > 

Service репозиторий для лиц:

@Service public class RepositoryService < private static List> repository = new ArrayList<>(); public List> getRepository() < return repository; >public List> addPerson(Person person) < repository.add(Arrays.asList(person.getFirstName(), person.getAge().toString())); return repository; >> 
public class Person < public Person(String firstName, Integer age) < this.firstName = firstName; this.age = age; >private String firstName; private Integer age; public String getFirstName() < return firstName; >public Integer getAge() < return age; >> 
        
Добавить лицо


Поиск

Поиск для: $

image

Приложение будет обрабатывать две команды «save» и «search» лица (см. контроллер). Всю работу по обработке (мапингу) входных параметров, берет на себя Spring.

Некоторые пояснения к шаблону.

здесь проверяется, если параметр задан, то вывести фразу «Поиск для: ..», иначе ничего:

здесь тоже сделана проверка, что список лиц присутствует, иначе пустой. Эти проверки важны при первом открытии страницы, иначе пришлось бы их инициализировать в index(), контроллера.

Источник

Java HTML Templating with Handlebars and Undertow

Previously on Handling Content Types with Undertow we showed how to send a simple HTML response. That is a little too basic for our use case. However, JSP, JSF, Spring MVC. all seem like they have a bit of learning curve. All we really need is to pass an object to a template and render some HTML, nothing fancy. Let’s take this a step further and follow the node / express approach of simply plugging in a HTML templating engine. Enter Handlebars, perfect, fairly simple syntax added to plain HTML anyone should be able to pick this up immediately (Yes MVC frameworks can use this also but do we need a framework for what a single class can do?). It also convienetly has ports in many languages. This means we can use the same templates client side (javascript) and server side if we want.

HTML Templating Utility

This is a rare case where we decided to make a simple abstraction hiding the underlying jknack handlebars implementation. Since it only really needs a few methods we can hide the implementation and easily swap it out later. Notice how we have a few config options. When we are running locally we want handlebars templates to be compiled on the fly and NOT cached. We also utilize HTML compression for all of the HTML specific methods. We also offer some non HTML templating methods. Sometimes it might make sense to abuse a HTML templating library to solve a similair problem.

public class Templating < private static final Logger log = LoggerFactory.getLogger(Templating.class); private static final MapNO_DATA = Maps.newHashMapWithExpectedSize(0); // Once again using static for convenience use your own DI method. private static final Templating DEFAULT; static < Templating.Builder builder = new Templating.Builder() .withHelpers(new TemplateHelpers()) .withHelper("md", new MarkdownHelper()) .withHelper(AssignHelper.NAME, AssignHelper.INSTANCE) .register(HumanizeHelper::register); // Don't cache locally, makes development annoying if (Env.LOCAL != Env.get()) < builder.withCaching() .withResourceLoaders(); >else < String root = AssetsConfig.assetsRoot(); builder.withLocalResourceLoaders(root); >DEFAULT = builder.build(); > public static Templating instance() < return DEFAULT; >private final Handlebars handlebars; private final HtmlCompressor compressor = new HtmlCompressor(); Templating(Handlebars handlebars) < this.handlebars = handlebars; >public String renderHtmlTemplate(String templateName) < return renderHtmlTemplate(templateName, NO_DATA); >public String renderHtmlTemplate(String templateName, Object data) < String response = renderTemplate(templateName, data); return compressor.compress(response); >public String renderTemplate(String templateName) < return renderTemplate(templateName, NO_DATA); >public String renderTemplate(String templateName, Object data) < Template template; try < template = handlebars.compile(templateName); >catch (IOException e) < throw new RuntimeException(e); >return render(template, data); > public String renderRawHtmlTemplate(String rawTemplate) < return renderRawTemplate(rawTemplate, NO_DATA); >public String renderRawHtmlTemplate(String rawTemplate, Object data) < String response = renderRawTemplate(rawTemplate, data); return compressor.compress(response); >public String renderRawTemplate(String rawTemplate) < return renderRawTemplate(rawTemplate, NO_DATA); >public String renderRawTemplate(String rawTemplate, Object data) < Template template; try < template = handlebars.compileInline(rawTemplate); >catch (IOException e) < throw new RuntimeException(e); >return render(template, data); > private String render(Template template, Object data) < try < // Can't currently get the jackson module working not sure why. MapjsonMap = Json.serializer().mapFromJson(Json.serializer().toString(data)); if (log.isDebugEnabled()) < log.debug("rendering template " + template.filename() + "\n" + Json.serializer().toPrettyString(jsonMap)); >return template.apply(jsonMap); > catch (IOException e) < throw new RuntimeException(e); >> static class Builder < private final Handlebars handlebars = new Handlebars(); private final Listloaders = Lists.newArrayList(); public Builder() < >public Builder withResourceLoaders() < log.debug("using resource loaders"); loaders.add(new ClassPathTemplateLoader()); loaders.add(new ClassPathTemplateLoader(TemplateLoader.DEFAULT_PREFIX, ".sql")); return this; >public Builder withLocalResourceLoaders(String root) < log.debug("using local loaders"); loaders.add(new FileTemplateLoader(root)); loaders.add(new FileTemplateLoader(root, ".sql")); return this; >public Builder withCaching() < log.debug("Using caching handlebars"); handlebars.with(new ConcurrentMapTemplateCache()); return this; >public Builder withHelper(String helperName, Helper helper) < log.debug("using template helper <>" , helperName); handlebars.registerHelper(helperName, helper); return this; > public Builder withHelpers(Object helpers) < log.debug("using template helpers <>" , helpers.getClass()); handlebars.registerHelpers(helpers); return this; > public Builder register(Consumer consumer) < log.debug("registering helpers"); consumer.accept(handlebars); return this; >public Templating build() < handlebars.with(loaders.toArray(new TemplateLoader[0])); return new Templating(handlebars); >> > 

Undertow HTML Templating Sender

A few simple lines and we can now send HTML templates with Undertow.

default void sendRawHtmlTemplate(HttpServerExchange exchange, String rawTemplate, Object data) < exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html"); exchange.getResponseSender().send(Templating.instance().renderRawHtmlTemplate(rawTemplate, data)); >default void sendHtmlTemplate(HttpServerExchange exchange, String templateName, Object data) < exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html"); exchange.getResponseSender().send(Templating.instance().renderHtmlTemplate(templateName, data)); >

Undertow HTML Templating Server

Routes for the Handlers below.

private static final HttpHandler ROUTES = new RoutingHandler() .get("/messageRawTemplate", HandlebarsHandlers::messageRawTemplate) .get("/messagesRawTemplate", HandlebarsHandlers::messagesRawTemplate) .get("/messagesTemplate", HandlebarsHandlers::messagesTemplate) ; public static void main(String[] args)

Undertow HTML Templating Handlers

Simple Raw Handlebars HTML Template

Simple inline Java Handlebars template with variable substitution.

private static final String messageTemplate = "

hello >

"; public static void messageRawTemplate(HttpServerExchange exchange) < String message = Exchange.queryParams().queryParam(exchange, "message").orElse("world"); Mapdata = Maps.newHashMap(); data.put("message", message); Exchange.body().sendRawHtmlTemplate(exchange, messageTemplate, data); >
curl localhost:8080/messageRawTemplate?message=StubbornJava 

hello StubbornJava

Iterating Raw Handlebars HTML Template

Simple inline Java Handlebars template with iteration substitution.

private static final String messagesTemplate = ">

Hello >

>"; public static void messagesRawTemplate(HttpServerExchange exchange) < String message = Exchange.queryParams().queryParam(exchange, "message").orElse("world"); int num = Exchange.queryParams().queryParamAsInteger(exchange, "num").orElse(5); Listmessages = Lists.newArrayList(); for (int i = 0; i < num; i++) < messages.add(message + " " + i); >Map data = Maps.newHashMap(); data.put("messages", messages); Exchange.body().sendRawHtmlTemplate(exchange, messagesTemplate, data); >
curl 'localhost:8080/messagesRawTemplate?message=StubbornJava&num=3' 

Hello StubbornJava 0

Hello StubbornJava 1

Hello StubbornJava 2

Handlebars HTML Template with CSS

Java Handlebars template from resource files with layout, includes, and iteration. Now this is starting to look like a real website. Find the templates here.

public static void messagesTemplate(HttpServerExchange exchange) < String message = Exchange.queryParams().queryParam(exchange, "message").orElse("world"); int num = Exchange.queryParams().queryParamAsInteger(exchange, "num").orElse(5); Listmessages = Lists.newArrayList(); for (int i = 0; i < num; i++) < messages.add(message + " " + i); >Map data = Maps.newHashMap(); data.put("messages", messages); Exchange.body().sendHtmlTemplate(exchange, "examples/handlebars/messages", data); > 
curl 'localhost:8080/messagesTemplate?message=StubbornJava&num=3'           

Hello StubbornJava 0

Hello StubbornJava 1

Hello StubbornJava 2

These examples are better to clone the repo and run locally. The HTML compression will smash everything on one line. The final example includes all CSS / JS from bootstrap using the public CDN. To take this a step further you can integrate with webpack and npm to manage your javascript and assets. If you are not a strong HTML / CSS developer consider using a site template to make your website stand out.

Источник

Читайте также:  Apache spark examples java
Оцените статью