1. Общ преглед
В този урок ще разгледаме библиотеката Handlebars.java за лесно управление на шаблони.
2. Зависимости на Maven
Нека започнем с добавянето на зависимостта на кормилото :
com.github.jknack handlebars 4.1.2
3. Прост шаблон
Шаблонът на кормилото може да бъде всякакъв вид текстов файл. Състои се от маркери като {{name}} и {{#each people}}.
След това попълваме тези тагове, като предаваме контекстен обект, като Map или друг обект.
3.1. Използвайки това
За да предадем една стойност на String в нашия шаблон, можем да използваме всеки обект като контекст. Трябва също да използваме {{ this}} t ag в нашия шаблон.
След това Handlebars извиква метода toString на контекстния обект и замества маркера с резултата:
@Test public void whenThereIsNoTemplateFile_ThenCompilesInline() throws IOException { Handlebars handlebars = new Handlebars(); Template template = handlebars.compileInline("Hi {{this}}!"); String templateString = template.apply("Baeldung"); assertThat(templateString).isEqualTo("Hi Baeldung!"); }
В горния пример първо създаваме екземпляр на Handlebars, нашата API входна точка.
След това даваме на този екземпляр нашия шаблон. Тук просто предаваме шаблона вграден, но след малко ще видим някои по-мощни начини.
И накрая, ние даваме на компилирания шаблон нашия контекст. {{this}} просто ще завърши с извикване на toString, поради което виждаме „Здравей, Baeldung!“ .
3.2. Предаване на карта като контекстен обект
Току-що видяхме как да изпратим String за нашия контекст, сега нека опитаме Map :
@Test public void whenParameterMapIsSupplied_thenDisplays() throws IOException { Handlebars handlebars = new Handlebars(); Template template = handlebars.compileInline("Hi {{name}}!"); Map parameterMap = new HashMap(); parameterMap.put("name", "Baeldung"); String templateString = template.apply(parameterMap); assertThat(templateString).isEqualTo("Hi Baeldung!"); }
Подобно на предишния пример, ние компилираме нашия шаблон и след това предаваме контекстния обект, но този път като Map .
Също така обърнете внимание, че използваме {{name}} вместо {{this}} . Това означава, че нашата карта трябва да съдържа ключа, името .
3.3. Предаване на потребителски обект като контекстен обект
Също така можем да предадем персонализиран обект на нашия шаблон:
public class Person { private String name; private boolean busy; private Address address = new Address(); private List friends = new ArrayList(); public static class Address { private String street; } }
Използвайки класа Person , ще постигнем същия резултат като предишния пример:
@Test public void whenParameterObjectIsSupplied_ThenDisplays() throws IOException { Handlebars handlebars = new Handlebars(); Template template = handlebars.compileInline("Hi {{name}}!"); Person person = new Person(); person.setName("Baeldung"); String templateString = template.apply(person); assertThat(templateString).isEqualTo("Hi Baeldung!"); }
{{име}} в шаблона ни ще се разкрият в нашето лице обект и да получите стойността на име областта .
4. Шаблонни товарачи
Досега използвахме шаблони, които са дефинирани вътре в кода. Това обаче не е единственият вариант. Също така можем да четем шаблони от текстови файлове.
Handlebars.java осигурява специална поддръжка за четене на шаблони от контекста на classpath, файлова система или сървлет. По подразбиране Handlebars сканира пътя на класа, за да зареди дадения шаблон:
@Test public void whenNoLoaderIsGiven_ThenSearchesClasspath() throws IOException { Handlebars handlebars = new Handlebars(); Template template = handlebars.compile("greeting"); Person person = getPerson("Baeldung"); String templateString = template.apply(person); assertThat(templateString).isEqualTo("Hi Baeldung!"); }
И така, тъй като ние извикахме compile вместо compileInline, това е намек към Handlebars да търси /greeting.hbs в пътя на класа.
Въпреки това, ние също можем да конфигурираме тези свойства с ClassPathTemplateLoader :
@Test public void whenClasspathTemplateLoaderIsGiven_ThenSearchesClasspathWithPrefixSuffix() throws IOException { TemplateLoader loader = new ClassPathTemplateLoader("/handlebars", ".html"); Handlebars handlebars = new Handlebars(loader); Template template = handlebars.compile("greeting"); // ... same as before }
В този случай казваме на Handlebars да търси /handlebars/greeting.html в пътя на класа .
Finally, we can chain multiple TemplateLoader instances:
@Test public void whenMultipleLoadersAreGiven_ThenSearchesSequentially() throws IOException { TemplateLoader firstLoader = new ClassPathTemplateLoader("/handlebars", ".html"); TemplateLoader secondLoader = new ClassPathTemplateLoader("/templates", ".html"); Handlebars handlebars = new Handlebars().with(firstLoader, secondLoader); // ... same as before }
So, here, we've got two loaders, and that means Handlebars will search two directories for the greeting template.
5. Built-in Helpers
Built-in helpers provide us additional functionality when writing our templates.
5.1. with Helper
The with helper changes the current context:
{{#with address}} I live in {{street}}
{{/with}}
In our sample template, the {{#with address}} tag starts the section and the {{/with}} tag ends it.
In essence, we're drilling into the current context object – let's say person – and setting address as the local context for the with section. Thereafter, every field reference in this section will be prepended by person.address.
So, the {{street}} tag will hold the value of person.address.street:
@Test public void whenUsedWith_ThenContextChanges() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("with"); Person person = getPerson("Baeldung"); person.getAddress().setStreet("World"); String templateString = template.apply(person); assertThat(templateString).contains("I live in World
"); }
We're compiling our template and assigning a Person instance as the context object. Notice that the Person class has an Address field. This is the field we're supplying to the with helper.
Though we went one level into our context object, it is perfectly fine to go deeper if the context object has several nested levels.
5.2. each Helper
The each helper iterates over a collection:
{{#each friends}} {{name}} is my friend. {{/each}}
As a result of starting and closing the iteration section with {{#each friends}} and {{/each}} tags, Handlebars will iterate over the friends field of the context object.
@Test public void whenUsedEach_ThenIterates() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("each"); Person person = getPerson("Baeldung"); Person friend1 = getPerson("Java"); Person friend2 = getPerson("Spring"); person.getFriends().add(friend1); person.getFriends().add(friend2); String templateString = template.apply(person); assertThat(templateString) .contains("Java is my friend.", "Spring is my friend."); }
In the example, we're assigning two Person instances to the friends field of the context object. So, Handlebars repeats the HTML part two times in the final output.
5.3. if Helper
На последно място, в случай помощник предоставя условно рендиране .
{{#if busy}} {{name}} is busy.
{{else}} {{name}} is not busy.
{{/if}}
В нашия шаблон предоставяме различни съобщения според заетото поле.
@Test public void whenUsedIf_ThenPutsCondition() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("if"); Person person = getPerson("Baeldung"); person.setBusy(true); String templateString = template.apply(person); assertThat(templateString).contains("Baeldung is busy.
"); }
След компилирането на шаблона задаваме контекстния обект. Тъй като заетото поле е вярно , крайният изход става
Baeldung е зает.
.6. Помощници за персонализирани шаблони
Също така можем да създадем свои собствени помощници.
6.1. Помощник
Интерфейсът на помощника ни позволява да създадем помощник на шаблон.
Като първа стъпка трябва да осигурим изпълнение на Helper :
new Helper() { @Override public Object apply(Person context, Options options) throws IOException { String busyString = context.isBusy() ? "busy" : "available"; return context.getName() + " - " + busyString; } }
As we can see, the Helper interface has only one method which accepts the context and options objects. For our purposes, we'll output the name and busy fields of Person.
After creating the helper, we must also register our custom helper with Handlebars:
@Test public void whenHelperIsCreated_ThenCanRegister() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); handlebars.registerHelper("isBusy", new Helper() { @Override public Object apply(Person context, Options options) throws IOException { String busyString = context.isBusy() ? "busy" : "available"; return context.getName() + " - " + busyString; } }); // implementation details }
In our example, we're registering our helper under the name of isBusy using the Handlebars.registerHelper() method.
As the last step, we must define a tag in our template using the name of the helper:
{{#isBusy this}}{{/isBusy}}
Notice that each helper has a starting and ending tag.
6.2. Helper Methods
When we use the Helper interface, we can only create only one helper. In contrast, a helper source class enables us to define multiple template helpers.
Moreover, we don't need to implement any specific interface. We just write our helper methods in a class then HandleBars extracts helper definitions using reflection:
public class HelperSource { public String isBusy(Person context) { String busyString = context.isBusy() ? "busy" : "available"; return context.getName() + " - " + busyString; } // Other helper methods }
Since a helper source can contain multiple helper implementations, registration is different than the single helper registration:
@Test public void whenHelperSourceIsCreated_ThenCanRegister() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); handlebars.registerHelpers(new HelperSource()); // Implementation details }
We're registering our helpers using the Handlebars.registerHelpers() method. Moreover, the name of the helper method becomes the name of the helper tag.
7. Template Reuse
The Handlebars library provides several ways to reuse our existing templates.
7.1. Template Inclusion
Template inclusion is one of the approaches for reusing templates. It favors the composition of the templates.
Hi {{name}}!
This is the content of the header template – header.html.
In order to use it in another template, we must refer to the header template.
{{>header}} This is the page {{name}}
We have the page template – page.html – which includes the header template using {{>header}}.
When Handlebars.java processes the template, the final output will also contain the contents of header:
@Test public void whenOtherTemplateIsReferenced_ThenCanReuse() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("page"); Person person = new Person(); person.setName("Baeldung"); String templateString = template.apply(person); assertThat(templateString) .contains("Hi Baeldung!
", "This is the page Baeldung
"); }
7.2. Template Inheritance
Alternatively to composition, Handlebars provides the template inheritance.
We can achieve inheritance relationships using the {{#block}} and {{#partial}} tags:
{{#block "intro"}} This is the intro {{/block}} {{#block "message"}} {{/block}}
By doing so, the messagebase template has two blocks – intro and message.
To apply inheritance, we need to override these blocks in other templates using {{#partial}}:
{{#partial "message" }} Hi there! {{/partial}} {{> messagebase}}
This is the simplemessage template. Notice that we're including the messagebase template and also overriding the message block.
8. Summary
In this tutorial, we've looked at Handlebars.java to create and manage templates.
We started with the basic tag usage and then looked at the different options to load the Handlebars templates.
Проучихме и помощниците на шаблони, които предоставят голяма част от функционалността. И накрая, разгледахме различните начини за повторно използване на нашите шаблони.
И накрая, проверете изходния код за всички примери на GitHub.