Make <p> appear and dissapear in Thymeleaf according to variable - thymeleaf

Hello I am building an application in Spring Boot and Thymeleaf and I have a paragraph that I want to make it appear only if it has a value. If it does not I do not want it to appear.
Here is the code that I have tried:
<h2 th:text="'Raspuns: ' + ${raspuns}" th:disabled="${raspuns}==null"></h2>
But when I enter the page it says: Raspuns: null I want to make that dissapear.

try this:
<h2 th:if="${raspuns} != null" th:text="'Raspuns: ' + ${raspuns}"></h2>
see more about conditions in the documentation:
Thymeleaf Conditional Evaluation

Related

Escaping ampersand in custom attribute using Thymeleaf 3?

Is it possible to do basic escaping (of ampersand, in my case) when generating a custom attribute? I have tried many ways (with normal escaping, th:text, th:utext, th:attr for all the dynamic attributes, substituting a custom tag in my Spring code), unfortunately found just some workaround, which is listed below.
Basically, it's about an AngularJS application with a piece of Thymealeaf 3 template:
<script th:inline="javascript">
function customSubmit() {
/*<![CDATA[*/
return /*[(${DIALOG_NAME} + '.$valid && submit()')]*/ null;
/*]]>*/
}
</script>
<form th:name="${DIALOG_NAME}"
th:action= "'/' + ${MODULE} + '.' + ${DIALOG_NAME}"
th:ng-app="${DIALOG_NAME} + 'App'"
th:ng-controller="${DIALOG_NAME} + 'Controller'"
ng-submit="customSubmit()"
...
>
...
</form>
What I am trying to make is one construct like
th:ng-submit="some Thymeleaf expression"
that generates the custom attribute value with the && within:
ng-submit="someDialog.$valid && submit()"
without any function redirection like in the workaround above.
Beside extending Thymeleaf (I am using SpringStandard dialect), is any straightforward way to generate such strings?
Thank you for any suggestion.
Ampersands (&) should be HTML-escaped in tag attributes so you can do it like this:
th:attr="ng-submit='some thymeleaf with && in it'"
EDIT:
If you also want to reference a value of some model attribute in the final form attribute value you have to use the expression preprocessing like this:
<form th:attr="ng-submit='__${DIALOG_NAME}__' + ' some ampersand && in it'">
</form>

Referencing variable inside template call - sightly

I'm trying to call a variable inside quotes inside a data-sly-template call. I would expect the output to include my string with the appropriate varible inside quotes. Below is the template and the string I'm using to call it:
Template:
<!-- template -->
<template data-sly-template.bnrButton="${ # style='String: button color class (default btn-primary)', classes='String: additional component button classes', text='String: button text (translation key)', defaultText='String: default button text (translation key)', link='String: link target for button (# is default)', fullWidth='Boolean: whether to display button in full width of container', noFollow='Boolean: if button should have a nofollow tag (no is def)', gaCategory='String: GA Category', gaEvent='String: GA Event', gaLabel='String: GA Label', gaAction='String: GA Action'}">
<a class="btn ${style || 'btn-primary'} hidden-print ${classes}${fullWidth ? ' btn-full-width' : ''}" role="button" href="${link || '#'}" rel="${noFollow ? 'nofollow' : ''}" onclick="${gaEvent # context = 'scriptString'}">${text || defaultText # i18n}</a>
</template>
<!-- call made to the template -->
<sly data-sly-call="${patterns.bnrButton # style='btn-secondary-light', classes='btn-sm', text=teaser.libraryButtonHeading, defaultText='View Library', link=teaser.myLibraryLink.href, fullWidth='true', newWindow='false', gaEvent='trackEvent('Test 1','Test 2','${teaser.teaserMessage}')'}"></sly>
If tried a number of combinations to get teaser.teaserMessage to print the authored message, but have been having issues because the patterns call is already inside quotes. I want to be able to pass a single string (called in the template call) to the template that includes all the information it needs for the onclick.
Thoughts?
Thank you.
You can use data-sly-test.variable_name before the template call to store the value into a variable:
<sly data-sly-test.gaEvent="${'trackEvent('Test 1','Test 2','{0}')' # format=teaser.teaserMessage}"
data-sly-call="${patterns.bnrButton # ..., gaEvent=gaEvent }"></sly>

Thymeleaf nested condition in th:with

I would like to do sommeting like that:
<div id="header_nav" th:fragment="header_nav (someId)" th:with="navPrefix=${'/content' + (someId ? ('/'+someId) : '')"}">
and use it later as *{navPrefix} within the div. I somehow don't get it with the condition nesting.
Can anyone help me?
Thanx!
I suspect this is because you're using th:include when you use the fragment. According to the Thymeleaf Documentation th:include simply includes the fragments content:
Whereas th:include will include the contents of the fragment into its host tag, th:replace will actually substitute the host tag by the fragment’s
If you're using th:include then your th:with won't be getting included, so it will always be blank. You can observe this with other attributes in the same element as the th:fragment declaration, such as style.
You can get around this by using th:replace instead, which will swap the entire fragment, not just the contents. Or, you can wrap your fragment contents with a th:block which you can use to define navPrefix:
<div th:fragment="header_nav(someId)">
<th:block th:with="navPrefix = ${'/content' + (someId != null ? ('/' + someId) : '')} ">
... contents of fragment ...
</th:block>
</div>
The only issues I see are the extra double quotes at the end, and your ternary operator doesn't contain a boolean expression when you pass in a String.
The following works to display either the prefix or the passed parameter within the block:
<div id="header_nav"
th:fragment="header_nav(someId)"
th:with="navPrefix = ${'/content' + (someId != null ? ('/' + someId) : '')} ">
<div th:text="${someId}"></div>
<div th:text="${navPrefix}"></div>
</div>

md-autocomplete in angular material - how to keep the class "md-not-found"

The md-autocomplete provides a class named md-not-found in the md-virtual-repeat-container when you are trying to search for an element that does not exist in the dropdown, displaying an error message underneath. When you remove focus from the input element, the md-not-found is removed. The autocomplete therefore gives a false impression of having a valid input, as the user is not presented with any feedback.
Is there any way to keep the class "md-not-found", even after you unfocus the input element?
md-autocomplete official demo: https://material.angularjs.org/latest/demo/autocomplete
Update
I have made a temporary solution:
<label class="{{selectedItem !== null || searchText === '' ? '' : 'label-error'}}">Name</label>
The label-error class applies a red color.
The solution is not an answer to the question per se, but offers an alternative quick fix
I used md-autocomplete inside the md-chips and its working as well as you want.
When request return noContent(204) md-not-found is being visible and it isn't disappear until user start texting again.
<md-content layout="column">
<md-chips
class="md-input"
ng-model="myItem"
md-autocomplete-snap
md-on-add="change()"
md-on-remove="change()"
required
md-require-match="true"
md-transform-chip="reformr($chip)"
md-separator-keys="keys">
<md-autocomplete md-selected-item="selectedItem"
md-no-cache="true"
md-search-text="search.text"
md-items="item in getSuggestedItems()"
md-item-text="item.name"
md-min-length="0"
placeholder="{{ 'textItemName' | translate }}"
required
md-input-name="suggestedItem"
md-search-text-change="listSuggestedItems(search.text)">
<span md-highlight-text="search.text" md-highlight-flags="^i">{{item.name}}</span>
<md-not-found>
{{'no_item_found' | translate}}
</md-not-found>
</md-autocomplete>
</md-content>

Mechanize not recognizing anchor tags via CSS selector methods

(Hope this isn't a breach of etiquette: I posted this on RailsForum, but I haven't been getting much response from there recently.)
Has anyone else had problems with Mechanize not recognizing anchor tags via CSS selectors?
The HTML looks like this (snippet with white space removed for clarity):
<td class='calendarCell' align='left'>
10
<p style="margin-bottom:15px; line-height:14px; text-align:left;">
<span class="sidenavHeadType">
Current Events</span><br />
<b><a href="http://www.mysite.org/index.php/site/
Clubs/banks_and_the_fed" class="a2">Banks and the Fed</a></b>
<br />
10:30am- 11:45am
</p>
I'm trying to collect the data from these events. Everything is working except getting the anchor within the <p>. There's clearly an <a> tag inside the <b>, and I'm going to need to follow that link to get further details on this event.
In my rake task, I have:
agent.page.search(".calendarCell,.calendarToday").each do |item|
day = item.at("a").text
item.search("p").each do |e|
anchor = e.at("a")
puts anchor
puts e.inner_html
end
end
What's interesting is that the item.at("a") always returns the anchor. But the e.at("a") returns nil. And when I do inner_html on the p element, it ignores the anchor entirely. Example output:
nil
<span class="sidenavHeadType">
Photo Club</span><br><b>Indexing Slide Collections</b>
<br>
2:00pm- 3:00pm
However, when I run the same scrape directly with Nokogiri:
doc.css(".calendarCell,.calendarToday").each do |item|
day = item.at_css("a").text
item.css("p").each do |e|
link = e.at_css("a")[:href]
puts e.inner_html
end
end
It recognizes the inside the , and it will return the href, etc.
<span class="sidenavHeadType">
Bridge Party</span><br><b>Party Bridge</b>
<br>
7:00pm- 9:00pm
Mechanize is supposed to use Nokogiri, so I'm wondering if I have a bad version or if this affects others as well.
Thanks for any leads.
Never mind. False alarm. In my Nokogiri task, I was pointing to a local copy of the page that included the anchors. The live page required a login, so when I browsed to it, I could see the a tags. Adding the login to the rake task solved it.

Resources