Parameter and view naming collisions in Play/Scala templates - scala

I am new to Play Framework and still trying to wrap my head around some things with the new Scala template engine.
Let's say I have the following package structure:
app/
app/controllers/Items.scala
app/models/Item.scala
app/views/layouts/page.scala.html
app/views/item/show.scala.html
app/views/item/details.scala.html //partial
And this is my item/show template:
#(item: Item, form: Form[Item])(implicit flash: Flash)
#layout.page() {
#*want to include details partial, wont work due to item param*#
#item.details(item)
}
Since including another template (e.g. including item/details above) is the exact same syntax as accessing a template parameter (e.g. item above), obviously this existing naming convention won't work without something changing.
I know I can rename my "app.views.item" package to "app.views.items", and rely on singular/plural forms to differentiate the view from the param name, but this does not seem like a very straightforward solution. Also what if I really want the parameter name to be the same as the view package?
One idea I have is to prepend all my views with an extra top level package:
app/views/views/item/details.scala.html
So the include syntax would be #views.item.details(), but again this is obviously a hack.
What is a good way to avoid this issue? How can I better organize my code to avoid such naming collisions?
Most other template engines use operations like "include" or "render" to specify a partial include. I don't mean to offend anyone here, but is the Play Scala template engine syntax so terse that it actually dictates the organization of code?

3 solutions:
First
Typpicaly for partial templates you should use tags as described in the docs, where app/views/tags folder is a base:
file: app/views/tags/product.scala.html
in the templates (no initial import required in the parent view full syntax will allow you to avoid name-clash: #tags.packageName.tagName()):
<div id="container">
#tags.product(item)
</div>
Of course in your case you can also use packages in the base folder
file: app/views/tags/item/product.scala.html
<div id="container">
#tags.item.product(item)
</div>
I'm pretty sure that'll solve your problem.
Second
To avoid clash without changing package's name you can just rename the item in your view, also I recommend do not use a form name for the Form[T] as it can conflict with helpers:
#(existingItem: Item, existingItemForm: Form[Item])(implicit flash: Flash)
#layout.page() {
#item.details(existingItem)
}
Third
If you'll fill your Form[Item] before passing to the view with given Item object, you don't need to pass both, as most probably you can get data from the form:
#(itemForm: Form[Item])(implicit flash: Flash)
#layout.page() {
<div>Name of item is: #itemForm("name").value (this is a replacemnet for ##existingItem.name </div>
#item.details(itemForm)
}
Of course in you product.scala.html you'll need to change the #(item: Item) param to #(itemForm: Form[Item])

Related

Make twig plugins by dynamically horizontal reusing via "use" (not "include")

Need: A dynamic template loaded from a DB
I need to present a JSON object via "template plugins" that will come from a database (defined outside the application itself). The plugin will be applied only if a plugin exists.
For this example, let's assume I have this object of type "Reservation" that contains a sub-object of type "Flight":
{
"id": "ABC-XYZ",
"reservationDate": "2020-09-23",
"state": "paid",
"flight":
{
"origin": "BCN",
"destination": "MAD",
"airline": "VY"
}
}
Rules
The controller will call a page template passing multiple objects.
The page template will "use" or "include" (see later more info) an object.html.twig and will display it.
The object.html.twig will do this:
If there's not any known plugin able to handle this type of object, the template will display a <pre> with the object converted to YAML. This will be mainly act as a "default" plugin or "fallback" plugin.
If there's a known plugin able to handle the object, the object will be sent to the plugin (which is not anything else than another twig template).
In this case, the plugin should be able to separate "parts" of "interpretable" results to make them "nice" and leave the rest into an object that will be, in turn, displayed again with the original "default" plugin.
If there are parts of the object that are in turn interpretable, they will be in turn passed to other plugins.
Example "desired" outputs
Sample 1. No plugin available
Sample 2. Plugin 'reservation' available. Interprets the state in green. Also removes the redundant data of the ID
Sample 3. Same than 2 but also plugin 'flight' available, able to process the flight block. Formats the texts and makes a lookup of the airline full-name
Sample 4. Plugin 'flight' available, able to process the flight, that in turn knows that the origin and the destination are "airports" and passes them into the corresponding nested 'airport' plugin, because they are "reusable" objects not only in the "flight" plugin but also in many other places in the application, so they are defined appart
What I have already explored
I know that doing it via 'include' it could work. But let's take a look at the differences between 'use' and 'include':
The major difference between include and use in twig is that:
When you include a template, it's direct HTML 'inserted there' where you can use the {{ }} operator for printing and {% %} for control flow (set variables, ifs, fors, etc.). The renderer will process it straight forward. But defining a new block via {% block myNiceBlock %} is forbidden.
When you 'use' a template, it's pre-loaded, and blocks are permitted. There's no rendering of the included block. Then, from the caller, you use a {{ block( 'whatever' ) }} to tell the renderer to go and render that specific block.
The 'include' is more rudimentary. The use allows horizontal reusing and allows itself to auto-organize itself with other sub-blocks called by the parent block, all in one single file.
For example, in the airports example, if there are N images, in a include you should put the wrapper HTML directly in the file, do a loop and inside the loop write the inner HTML.
Instead in the use approach you'd do an airport block which in turn loops over the images and just calls the block airportImage which is defined in another block in the same file, thus facilitating clean-coding.
Requirement
The application should not be re-deployed when new plugins are created. They must be loaded from a DB or any other dynamic system, as the plugins will be written by "users of the application" as they need it. No deploy allowed.
The plugins should be written in terms of a "block-able" twig template, so need to be 'use'-able.
Question
Discovering "which" plugin to call is not a problem. Assume that whoever (the controller, the twig itself, whoever really) can discover for this example that a "reservation" plugin exists somewhere. How can I use it from the page? When the reservation is rendering it "asks if a flight plugin" is available. If not, all to the YAML. If it is, how can then dynamically tell the reservation to use the flight?
In short: How do I force a template to dynamically use (not include) templates that, in turn, comes from the database (not from fixed files)?
NOTE: If this info is useful: I'm using Symfony 5 with webpack.
Thanks!

How to use selector

Let's say, I have a template A and sling:resourceType is /apps/myproject/components/basePage. In this component I've body.html and header.html and footer.html script included through slightly in body.html.
Now I am creating another template B, and sling:resourceType is /apps/myproject/components/compB and sling:resourceSuperType of compB is /apps/myproject/components/basePage.
In /apps/myproject/components/compB I have added content.html and selector.html
If I create a page (mytest.html) of type template B, then header and footer script is included correctly but when I hit this mytest.selector.html then header and footer script is not included. I want template B will have two different view based on selector.
Please let me know where I am missing.
I believe you are trying to include multiple scripts within same template to achieve different views. This is correct approach todo in AEM. But missing part is the moment you create the second script (selector.html in this case), it becomes another template and you need to code to include your entire page scripts into this script as well.
When you override scripts from /libs/wcm/foundation/components/page component, they ll work fine when your custom script names matches to parent component. For example your body.html will override /libs/wcm/foundation/components/page/body.html and page will render how it is coded. When you create selector.html it becomes independent script as there is no /libs/wcm/foundation/components/page/selector.html.
You need to define all behavior (to include header, footer script etc) explicitly against your custom script. In this case you need include header/footer scripts explicitly into your selector.html
Using a selector means that you're using some special implementation of your component. For instance, your component may have several charts and you want to encapsulate those in your selectors and use it through AJAX from browser, and reuse those selectors in your main component as well.
Currently, you're trying to achieve is to use your header and footer to another component which breaks the encapsulation rule. Rather do this, take out your header.html and footer.html and make those individual components and you it in your basePage as well as your child pages.
See the snippet below:
<div data-sly-resource="${'header' # resourceType='/apps/myproject/components/header'}">
<p>Your body and anything you want to put here</p>
<div data-sly-resource="${'footer' # resourceType='/apps/myproject/components/footer'}">
This way, you can reuse your headers whereever you want even in your selectors.

How can I include content of a component in Fabricator Assemble *without* a corresponding attribute, or at block level?

In Fabricator Assemble, I could have a component button.html:
<a class="button">{{text}}</a>
I can use this with the syntax {{>button text='Home'}}. Notably, I have to specify a name for the "text" attribute.
I'm looking to see how I can handle not needing to do that in Assemble. The Literals section of the docs for Handlebars (whiich Fabricator Assemble is built on) highlights an alternative syntax with which I could include a button:
{{>button 'Home'}}
In this example, "Home" is a value without any name for it at all. Handlebars also indicates the following is possible as a basic block:
{{#button}}
<b>Some button content</b>
{{/button}}
Likewise, that content has no name.
I'd like to be able to do this same thing in Fabricator Assemble, but it doesn't seem to have a way for me to include this nameless content. In templates there's {% body %} but that doesn't work here.
In Handlebars, which Fabricator Assemble is based on, all examples for how to recreate this involve JavaScript, which doesn't translate well to Assemble.
What can I do to use {{>button 'Some text'}} or {{#button}}...{{/button}} syntax in Fabricator Assemble? Is this behaviour even available?
In the current version, the easiest way to achieve this is with a custom helper.
Add the following to the helpers option in your gulpfile.js:
default: (value, defaultValue) => {
return value || defaultValue;
},
Then inside a handlebars template:
<div>
{{default varName 'default value'}}
</div>

Scala templates import reusable blocks (Play2)

I'm using Play framework 2.2.4 and Scala templates. I have created base Scala template with many code blocks, which I want to use in multiple views. Something like:
base.scala.html
#()
#display(product: Product) = {
#product.name ($#product.price)
}
products.scala.html
...
#display(product)
...
How can I import such file in view to use #display block?
Each view fragment should be in it's own file, with it's own parameters declared there. A Play template is supposed to work like a single function, not many. Instead, create a directory called base, and separate the view fragments into separate files.
views/base/display.scala.html
#(product: Product)
#product.name ($#product.price)
views/products.scala.html
...
#base.display(product)
...
Put it in a separate file, display.scala.html and make it the only/actual template, the file name is the fragment/function name:
#(product: Product)
#product.name ($#product.price)
if in the same package just call it
#display(product)
or if in another package either use full package name or import it first
#some.package.display(product)
#import some.package.display
#display(product)
Take a look into templating doc, section: Tags (they are just functions right?)
In general you can i.e. move your block to views/tags/displayProduct.scala.html (and use it as common template) so you can use it in ANY view with:
<div class="product">
#tags.displayProduct(product)
</div>

Using <wicket:message> tag to produce partially formatted text

I've read about wicket:message here, but can't seem to make it do everything I'd like.
Say I have a HTML page with <wicket:message key="text"/> and a properties file containing text=Blah blah: important point, foo bar. I'm wondering how to make part of the text bold (or apply arbitrary CSS to it), to achieve output like:
Blah blah: important point, foo bar
Note that none of this is actually dynamic, so I wouldn't want to do anything in Java, if that can be avoided.
I've tried nesting tags with something like the following, but no luck.
<wicket:message key="text">
<span class="bold"><wicket:message key="text2"/></span>
</wicket:message>
text=Blah blah: ${text2}, foo bar
text2=important point
Is this even possible in Wicket without 1) injecting the formatted part from Java side or 2) just splitting the text into (in this case) three different properties?
The easiest way is to put the tags inside your localization file:
text=Blah blah: <strong>text2</strong>, foo bar
You could also use a Label and a ResourceModel to replace it later:
text=Blah blah: [b]text2[/b], foo bar
And in your model getObject(), or in your Label:
string.replace("[b]", "<strong>");
string.replace("[/b]", "</strong>");
Or, even better, try to reuse a Markdown implementation in your Label.
I've managed to do this for my own application, albeit with a rather ugly hack. I did it by exposing a customized version of WicketMessageResolver.
Here's what to try:
Wholesale copy and paste org.apache.wicket.markup.resolver.WicketMessageResolver into your own class (say com.acme.CustomWicketMessageResolver) (the hack begins!)
Inside your CustomWicketMessageResolver change
WicketTagIdentifier.registerWellKnownTagName( "message" ); to something else like WicketTagIdentifier.registerWellKnownTagName( "msg" );.
Inside of
private void renderMessage(final MarkupStream markupStream, final ComponentTag openTag, final String key, final String value), you'll find the line getResponse().write( text );.
Immediately before that line you have the opportunity to screw around with the value of "text". There, I do something like text = MyLabelUtils.replaceWikiMarkup(text) which post-processes some wiki-like markup syntax used by the content authors for my application.
For example, I use this method to take a Label using a ResourceModel pointing to the key:
propertyKey=I found the answer on [acronym SO].
and a render it as
I found the answer on <acronym title="Stack Overflow">SO</acronym>.
and that method handles i18n and all that fun stuff.
You can, of course, extend that wiki syntax (or anything similar) to be as simple or complex as you'd need.
Note that you'll have to change <wicket:message key='foo'> to <wicket:msg key='foo> in all of your markup files (or at least in ones where you want this behaviour).
I'd obviously prefer a more standard way to customize the behaviour of the built-inwicket message resolver, but if you need this functionality in a pinch, like I did, this will work for now.
If you need something more standard, you could raise the issue on the Wicket mailing list. It's pretty good.
Starting from Wicket 1.4 you can nest components within a wicket:message element. For example:
<wicket:message key="myKey">
This text will be replaced with text from the properties file.
<span wicket:id="amount">[amount]</span>.
<a wicket:id="link">
<wicket:message key="linkText"/>
</a>
</wicket:message>
Then
myKey=Your balance is ${amount}. Click ${link} to view the details.
linkText=here
and
add(new Label("amount",new Model("$5.00")));
add(new BookmarkablePageLink("link",DetailsPage.class));
Results in:
Your balance is $5.00. Click here to view the details.
So maybe, nesting <wicket:message>s without a component could work as well. Not sure.
Source: https://cwiki.apache.org/confluence/display/WICKET/Wicket%27s+XHTML+tags#Wicket%27sXHTMLtags-Elementwicket%3Amessage