Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce TemplateInstance#setLocale and TemplateInstance#setVariant #40017

Merged
merged 2 commits into from
Apr 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions docs/src/main/asciidoc/qute-reference.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -1656,10 +1656,10 @@
<2> A regular expression `foo.*` disables validation for templates whose name is starting with `foo`.
<3> Injection fields are resolved as template locators annotated with `@Locate` are registered as singleton session beans.

=== Template Variants

Check warning on line 1659 in docs/src/main/asciidoc/qute-reference.adoc

View workflow job for this annotation

GitHub Actions / Linting with Vale

[vale] reported by reviewdog 🐶 [Quarkus.Headings] Use sentence-style capitalization in '4.2. Template Variants'. Raw Output: {"message": "[Quarkus.Headings] Use sentence-style capitalization in '4.2. Template Variants'.", "location": {"path": "docs/src/main/asciidoc/qute-reference.adoc", "range": {"start": {"line": 1659, "column": 19}}}, "severity": "INFO"}

Sometimes it's useful to render a specific variant of the template based on the content negotiation.
This can be done by setting a special attribute via `TemplateInstance.setAttribute()`:
This can be done by setting a special attribute via `TemplateInstance.setVariant()`:

[source,java]
----
Expand All @@ -1672,7 +1672,9 @@
ItemManager manager;

String renderItems() {
return items.data("items",manager.findItems()).setAttribute(TemplateInstance.SELECTED_VARIANT, new Variant(Locale.getDefault(),"text/html","UTF-8")).render();
return items.data("items", manager.findItems())
.setVariant(new Variant(Locale.getDefault(), "text/html", "UTF-8"))
.render();
}
}
----
Expand Down Expand Up @@ -2829,7 +2831,7 @@
Template hello;

String render() {
return hello.instance().setAttribute("locale", Locale.forLanguageTag("cs")).render(); <1>
return hello.instance().setLocale("cs").render(); <1>
}
}
----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

public final class MessageBundles {

public static final String ATTRIBUTE_LOCALE = "locale";
public static final String ATTRIBUTE_LOCALE = TemplateInstance.LOCALE;
public static final String DEFAULT_LOCALE = "<<default>>";

private static final Logger LOGGER = Logger.getLogger(MessageBundles.class);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.quarkus.qute;

import java.util.Locale;
import java.util.concurrent.CompletionStage;
import java.util.function.Consumer;
import java.util.function.Function;
Expand Down Expand Up @@ -31,6 +32,11 @@ public interface TemplateInstance {
*/
String SELECTED_VARIANT = "selectedVariant";

/**
* Attribute key - locale.
*/
String LOCALE = "locale";
gastaldi marked this conversation as resolved.
Show resolved Hide resolved

/**
* Set the the root data object. Invocation of this method removes any data set previously by
* {@link #data(String, Object)} and {@link #computedData(String, Function)}.
Expand Down Expand Up @@ -70,7 +76,6 @@ default TemplateInstance computedData(String key, Function<String, Object> funct
}

/**
*
* @param key
* @param value
* @return self
Expand All @@ -80,7 +85,6 @@ default TemplateInstance setAttribute(String key, Object value) {
}

/**
*
* @param key
* @return the attribute or null
*/
Expand Down Expand Up @@ -142,7 +146,6 @@ default CompletionStage<Void> consume(Consumer<String> consumer) {
}

/**
*
* @return the timeout
* @see TemplateInstance#TIMEOUT
*/
Expand All @@ -151,15 +154,13 @@ default long getTimeout() {
}

/**
*
* @return the original template
*/
default Template getTemplate() {
throw new UnsupportedOperationException();
}

/**
*
* @param id
* @return the fragment or {@code null}
* @see Template#getFragment(String)
Expand All @@ -178,6 +179,38 @@ default TemplateInstance onRendered(Runnable action) {
throw new UnsupportedOperationException();
}

/**
* Sets the {@code locale} attribute that can be used to localize parts of the template, i.e. to specify the locale for all
* message bundle expressions in the template.
*
* @param locale a language tag
* @return self
*/
default TemplateInstance setLocale(String locale) {
return setAttribute(LOCALE, Locale.forLanguageTag(locale));
}

/**
* Sets the {@code locale} attribute that can be used to localize parts of the template, i.e. to specify the locale for all
* message bundle expressions in the template.
*
* @param locale a {@link Locale} instance
* @return self
*/
default TemplateInstance setLocale(Locale locale) {
return setAttribute(LOCALE, locale);
}

/**
* Sets the variant attribute that can be used to select a specific variant of the template.
*
* @param variant the variant
* @return self
*/
default TemplateInstance setVariant(Variant variant) {
mkouba marked this conversation as resolved.
Show resolved Hide resolved
return setAttribute(SELECTED_VARIANT, variant);
}

/**
* This component can be used to initialize a template instance, i.e. the data and attributes.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -64,4 +65,33 @@ public void testComputeData() {
assertTrue(fooUsed.get());
assertFalse(barUsed.get());
}

@Test
public void testLocale() throws Exception {
Engine engine = Engine.builder().addDefaults()
.addValueResolver(ValueResolver.builder()
.applyToName("locale")
.resolveSync(ctx -> ctx.getAttribute(TemplateInstance.LOCALE))
.build())
.build();
Template hello = engine.parse("Hello {locale}!");
assertEquals("Hello fr!", hello.instance().setLocale(Locale.FRENCH).render());
}

@Test
public void testVariant() {
Engine engine = Engine.builder().addDefaults()
.addValueResolver(ValueResolver.builder()
.applyToName("variant")
.resolveSync(ctx -> ctx.getAttribute(TemplateInstance.SELECTED_VARIANT))
.build())
.addValueResolver(ValueResolver.builder()
.appliesTo(ctx -> ctx.getBase() instanceof Variant && ctx.getName().equals("contentType"))
.resolveSync(ctx -> ((Variant) ctx.getBase()).getContentType())
.build())
.build();
Template hello = engine.parse("Hello {variant.contentType}!");
String render = hello.instance().setVariant(Variant.forContentType(Variant.TEXT_HTML)).render();
assertEquals("Hello text/html!", render);
}
}
Loading