Setting up thymeleaf value to anchor tag and null check - spring-boot

I am setting thymeleaf anchr tag href as below to use query param,
<a th:href="#{'/page?vars='+${param.q1}+'&varr=' + ${param.q2}}">
the above is working fine. But sometimes, I get q1 url param will be null. In that case, I need to set default value.
I have tried like,
<a th:href="#{'/page?vars='+${param.q1 != null} ? ${param.q1} : 'default' +'&varr=' + ${param.q2}}">
But I am getting error on this page. Any suggestions on this?

You should be using Thymeleaf's standard URL syntax when generating links (rather than string concatenation). This expression should work for you:
<a th:href="#{/page(vars=${param.q1} ?: 'default',varr=${param.q2})}">

This should do the trick
<a th:href="#{'/page?vars='+ ${param.q1}?: 'default' +'&varr=' + ${param.q2}}">
Source : https://www.baeldung.com/spring-thymeleaf-conditionals#1-elvis-operator

Related

In golang, how do I use URLs for image link href and img src in html/template? [duplicate]

I'm using Golang in backend. When I render the html using html/templates I'm getting ZgotmplZ for URL's.
{{if .UserData.GitURL}}
<li>
<a href="{{.UserData.GitURL}}">
<i class="icon fa fa-github"></i>
</a>
</li>
{{end}}
I'm using string for GitURL in server side. This URL is https. When I looked for solutions some blog suggested to use safeURL. So I tried,
{{if .UserData.GitURL}}
<li>
<a href="{{.UserData.GitURL | safeURL}}">
<i class="icon fa fa-github"></i>
</a>
</li>
{{end}}
But code didn't compile.
Could someone help me with this? Any suggestion would be really helpful.
ZgotmplZ is a special value indicating your input was invalid. Quoting from the doc of html/template:
"ZgotmplZ" is a special value that indicates that unsafe content reached a
CSS or URL context at runtime. The output of the example will be
<img src="#ZgotmplZ">
If the data comes from a trusted source, use content types to exempt it
from filtering: URL(`javascript:...`).
If you want to substitute a valid url text, nothing special like like safeURL function is needed. If your template execution results in a value like "#ZgotmplZ", that means the URL you wanted to insert is invalid.
See this example:
t := template.Must(template.New("").Parse(`` + "\n"))
t.Execute(os.Stdout, "http://google.com")
t.Execute(os.Stdout, "badhttp://google.com")
Output:
You may use a value of type template.URL if you want to use a URL as-is without escaping. Note that in this case the provided value will be used as-is even if it is not a valid URL.
safeURL is not some kind of magic or predeclared function that you may use in templates. But you may register your own custom function which returns a string url parameter as a value of type template.URL:
t2 := template.Must(template.New("").Funcs(template.FuncMap{
"safeURL": func(u string) template.URL { return template.URL(u) },
}).Parse(`` + "\n"))
t2.Execute(os.Stdout, "http://google.com")
t2.Execute(os.Stdout, "badhttp://google.com")
Output:
Note: If you are able to pass in a template.URL value directly to the template execution, you do not need to register and use a safeURL() custom function:
t3 := template.Must(template.New("").Parse(`` + "\n"))
t3.Execute(os.Stdout, template.URL("http://google.com"))
t3.Execute(os.Stdout, template.URL("badhttp://google.com"))
Output:
Try these on the Go Playground.

Thymeleaf Template not rendering param value inside th if condition

I am using thymeleaf template for my spring boot application. Here below the main page,
<div th:replace="content :: content"></div>
and inside content fragment,
<div th:fragment="content">
<h4 th:if="${param.val== 'abc'}">SOME-TEXT</h4> // not working
<h4 th:if="${param.val== 'abc'}" th:text="${param.val}"></h4> // not working
<h4 th:text="${param.val}"></h4> // working and value is abc
<h4 th:unless="${param.val== 'abc'}" th:text="${param.val}"></h4> // working - value in html text is abc
<h4 th:unless="${param.val== 'abc'}">SOME-TEXT</h4> // Working, value is SOME-TEXT
</div>
URL: domain/?val=abc
I want to display: SOME-TEXT in html if param.val == 'abc'.
Value 'abc' is coming inside th:text. But inside th:if failing.
Seems some hidden extra strings added to param.val?
Any suggestion?
The Thymeleaf function ${param.val} will return a request parameter called val. But this could be a multivalued object (e.g. an array) - for example consider this (which is a valid construction):
?val=abc&val=def
So to work with a single-valued string, you can do this:
<h4 th:if="${#strings.toString(param.val)} == 'abc'" th:text="'SOME-TEXT-2'">SOME-TEXT-1</h4>
This prints SOME-TEXT-2 in the web page.
Or you can use this:
<h4 th:if="${#strings.toString(param.val)} == 'abc'">SOME-TEXT-1</h4>
Which prints SOME-TEXT-1.
Just out of interest, if you used that first example val=abc&val=def, then you can see what happens with this:
<h4 th:text="${param.val}"></h4>
It prints an array:
[abc, def]
You may see something like this when processing a series of related checkboxes (just as one example).
Update:
For a null-check, using Thymeleaf, you can do this:
<h4 th:if="${param.val} != null and
${#strings.toString(param.val)} == 'abc'">SOME-TEXT-2</h4>
In this specific case, it isn't really needed, as you are not doing anything with the null value which might cause a problem.
It's more relevant if you are chaining values in objects foo.bar.baz - and you need to check if foo or bar are null to avoid a null pointer exception.
Bear in mind that Spring's expression language has the safe navigation operator, which can be very helpful in such cases: foo.?bar.?baz, allowing you to write more concise null handling than with Thymeleaf alone. But again, not relevant to your specific example from the question.

How to use anchor link or HTML in ternary operator in thymeleaf

I encountered a problem that need to write some HTML codes in ternary operator in Thymeleaf. In where I need to chose an anchor link by using ternary operator. For better understand, I putted those problematic code in below:
<span th:text="${error_code == '404'} ? 'Home' : 'Login'"></span>
So, how can I wirte those code correclty in Themeleaf
This should do it :
<span th:utext="((${error_code} == '404') ? '<a href="http://localhost:8080/home">Home</a>' : '<a href="http://localhost:8080/login">Login</a>')"></span>
" is for escaping double quote in html.
utext is to tell thymeleaf not to print plain text as "< a href.. "

How to render HTML when inside {{}} on Brade with ternary operator in Laravel 5.7?

I have the follow code in Blade using a ternary operator:
<td>{{isset($arrTemp[$ccc->id]) ? "<a hfet='".url('/cc/'.$cc->id)."'>".count($arrTemp[$cc->id])."</a>": 'N/A'}}</td>
If it find somenthing for the array key $cc->id, should thisplay the value with the link atteched to it.
But the page is rendering <a hfet='http://my.test/cc/56526235'>4</a> the string itself.
What am I missing?
When you use {{ }} the output is automatically escaped to prevent XSS attacks. You can use {!! !!} instead, which will not escape the string.
Source: https://laravel.com/docs/5.4/blade#displaying-data

Can't get containts from xpath codeception

I have element
<a href="/s-xQ6qeR/documents/download?revid=28">
<span class="icon icon-file-pdf-o" style="vertical-align: middle"></span> test_upload_uwfacjtn.pdf
</a>
I need to check this element on page
I try do it:
$fileHref = $this->I->grabAttributeFrom("//a[contains(., 'test_upload_uwfacjtn.pdf')]", 'href');
But I got error:
Step Grab attribute from "//a[contains(.,
'test_upload_uwfacjtn.pdf')]","href" Fail Element that matches CSS
or XPath element with '//a[contains(., 'test_upload_uwfacjtn.pdf')]'
was not found.
I finded two way to check the text inside an html tag :
1. Using the method grabAttributeFrom and then compare the result
$fileName = $I->grabTextFrom('//a[#href="/s-xQ6qeR/documents/download?revid=28"]/span');
$I->assertEquals('test_upload_uwfacjtn.pdf', $fileName);
This can be usefull if you want to put the result inside a variable and use it for other tests later.
2. Using method seeElement with the text to compare inside your xpath
$I->seeElement('//span[text()="test_upload_uwfacjtn.pdf"]');

Resources