If statement inside checked attribute of input element in freemarker? - freemarker

Is it possible to write this in freemarker.
<input type="checkbox" value="Available ?" checked="<#if ${status}=='Available'>true<#else>false</#if>"/>
For now it throws exception
I want html checkbox to be checked if status property equals to "Available".
How to do this in freemarker?

<#if ${status}=='Available'> has a syntactical error (that the error message that you haven't included points to, I'm certain): you can't use ${...} inside FreeMarker tags (well, except inside string literals, but whatever). It should be just <#if status == 'Available'>. But, the simples solution for what you want is:
checked="${(status == 'Available')?c}"
or if you have an older FreeMarker then:
checked="${(status == 'Available')?string('true', 'false')}"

Related

Freemarker, looping sequence with one object/multiple attributes

I am working on looping through one object with multiple attributes. In my scenario, I am looking for external content values.
email_address
article01
article02
article03
email#address.com
Y
Y
These values can change all the time, so we have to define them manually every instance where we use this, but I want to be able to list them in a sequence and then loop through and include them when object.attribute=Y.
The below block is purely conceptual, but referencing the attribute within the expression is where I get confused.
<#assign seq = ['article01','article02','article03']>
<#list seq as articles>
<#if base.${article}="Y">
<#include "*/${article}.htm"/>
</#if>
</#list>
In this instance, the resulting code would be:
<html><article01.html content></html>
<html><article03.html content></html>
Assuming base.articel01 would work, you can use base[article] (instead of base.${article}).

FreeMarker if statement comparing two values

I'm trying to compare two values
<#if user.cellPhone != changedUser.cellPhon>
<br><span class="changes">*${changedUser.cellPhone}</span></#if>
I'm getting an error
freemarker.core.InvalidReferenceException: The following has evaluated to null or missing:==> changeUser
Tip:
If the failing expression is known to legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)??
Add null check to condition changedUser??:
<#if changedUser?? && user.cellPhone != changedUser.cellPhon>

Nokogiri: How to select the value of an attribute that contains periods in its id?

I've been working with Nokogiri for a couple of days and I absolutely adore it. Everything was working brilliantly until I got a requirement to scrape a website that uses the data-reactid javascript attribute tag. The problem is that Nokogiri seems to be getting confused with the attribute id format this website is using (several periods, some dollar signs and some other invalid xml/css characters):
An example of what I need to scrape would be:
<td data-reactid=".3.3.1:$contract_23.$=1$dataRow:0.1">94.280</td>
I need the value (94.280) inside of the attribute with an id of ".3.3.1:$contract_23.$=1$dataRow:0.1"
which usually in nokogiri we would select by doing something like:
doc.css("type[attributename=attributeid]")
in my example it would be:
doc.css("td[data-reactid=.3.3.1:$contract_23.$=1$dataRow:0.1]")
but no matter what I do to escape the invalid characters, it keeps telling me there is an invalid character after my equals sign:
Error message for code above:
nokogiri-1.4.3.1/lib/nokogiri/css/parser.rb:78:in `on_error': unexpected '.3' after 'equal'
I've tried:
a) Getting my string defined as a variable and forced into a string
b) Escaping it with backslashes (.3.[...])
c) Prefixing it with a hash (#.3.3[...])
d) Escaping it using cgi escapedString
e) Placing it inside '%{ }' eg '%{.3.3[...]}'
No matter what I do, I keep getting the same message (except for option e which gives me an altogether different error message:
: no .<digit> floating literal anymore; put 0 before dot
Can you guys help me get the right value with such an oddly-named attribute?
You didn't show how you are parsing your document, but if I parse it as HTML and then use single quotes around the attribute value in the css selector, I can get the tag:
require 'nokogiri'
html = <<END_OF_HTML
<td data-reactid="hello">10</td>
<td data-reactid=".3.3.1:$contract_23.$=1$dataRow:0.1">94.280</td>
<td data-reactid="goodbye">20</td>
END_OF_HTML
html_doc = Nokogiri::HTML(html)
html_doc.css("td[data-reactid='.3.3.1:$contract_23.$=1$dataRow:0.1']").each do |tag|
puts tag.text
end
--output:--
94.280
Check out the Mothereffing Unquoted Attribute Value Validator via this SO post:
CSS attribute selectors: The rules on quotes (", ' or none?)

Add spring macro as parameter to Freemarker macro

I have the code snippet below, and want to give the output from <#spring.message "name"/> as paraneter to the macro (the placeholder parameter).
Providing it directly as I tried doing below didnt't work, anyone knows how I should do it?
<td class="rightCell"><b><#spring.message "name"/>:</b></td>
<td class="leftCell"><#createUserInputItemModifiedv2 "name", "name", "text", #spring.message "name" /></td>
<#macro createUserInputItemModifiedv2 attributeName, errorMessageName, inputType, placeholder>
<input class="edit" type="${inputType}" id="${attributeName}" name="${attributeName}" placeholder="${placeholder}" value="${user[attributeName]!}"/><br/>
<#if validationErrors?? && validationErrors[attributeName]??>
<div class="errorMessage" id="${errorMessageName}Error">
${validationErrors[attributeName]!}
</div>
</#if>
</#macro>
That's because spring.message should also be a FreeMarker function, not just a FreeMarker macro. Macros has no return value (they might directly print to the output writer as a side-effect) so you can't call them where an expression is expected. Anyway... how to work this around right now. Looking at the source code of Spring, maybe this will work:
<#function message code><#return springMacroRequestContext.getMessage(code)></#function>
You could create a utils.ftl or something, (auto-)#import it as u, and then you can do <#createUserInputItemModifiedv2 ..., u.message("name")> in your templates. (Actually, it could be made more convenient, so that you can just write msg.name or like, but let's not go into that here.)
However, I'm not sure if there's any backward compatibility guarantee regarding springMacroRequestContext or its content. So ultimately this should be fixed in Spring.

Handling null values in Freemarker

How to handle null values in Freemarker? I get some exceptions in the template when null values are present in data.
Starting from freemarker 2.3.7, you can use this syntax :
${(object.attribute)!}
or, if you want display a default text when the attribute is null :
${(object.attribute)!"default text"}
You can use the ?? test operator:
This checks if the attribute of the object is not null:
<#if object.attribute??></#if>
This checks if object or attribute is not null:
<#if (object.attribute)??></#if>
Source: FreeMarker Manual
I think it works the other way
<#if object.attribute??>
Do whatever you want....
</#if>
If object.attribute is NOT NULL, then the content will be printed.
Use ?? operator at the end of your <#if> statement.
This example demonstrates how to handle null values for two lists in a Freemaker template.
List of cars:
<#if cars??>
<#list cars as car>${car.owner};</#list>
</#if>
List of motocycles:
<#if motocycles??>
<#list motocycles as motocycle>${motocycle.owner};</#list>
</#if>
I would like to add more context if you have issues and this is what I have tried.
<#if Recipient.account_type?has_content>
… (executes if variable exists)
<#else>
… (executes if variable does not exist)
</#if>
This is more like Javascript IF and ELSE concept where we want to check whether this value or another chaining through required logic.
Freemarker webite
Other reference:
Scenario: Customer has ID and name combined like 13242 Harish, so where our stakeholder need the only name, so I have tried this ${record.entity?keep_after(" ")} and it did work, however, it can only work when you have space, but when a customer doesn't have space and one name, I had to do some IF ELSE condition to check Null value.
Use:
${(user.isSuperman!false)?c}
It will work when "isSuperman" is null and when have boolean value
What we want:
For "null" we want to output 'false'
For boolean value and want to output value ('true' or 'false')
What we know:
boolean need to convert to string by using "?c" see Built-ins for booleans
but null we cannot convert to string and we need to use "!" see Handling missing values

Resources