I have a double variable that can have values like 45, 45.57, 234.1
Currently
[[${number} ]]
will print above numbers as
45.0
45.57
234.1
I want 45.0 to print as 45 while leaving others same as before.
How to do that in thymeleaf 3?
#numbers.formatDecimal
this is not found in official docs for thymeleaf. So dont know how to use that.
Documentation is at the following link:
https://www.thymeleaf.org/apidocs/thymeleaf/3.0.9.RELEASE/org/thymeleaf/expression/Numbers.html
But there is no such method in the current version of Thymeleaf(3.0.9). You can write you own utility class and use it in your Thymeleaf pages. For example:
public final class NumberFormatterUtils {
public static String formatNumber(double number) {
NumberFormat nf = new DecimalFormat("##.###");
return nf.format(number);
}
}
And then:
<span th:text="${T(packageName.NumberFormatterUtils).formatNumber(number)}" ></span>
Related
I know how to split the string within a Controller or Domain class.
But i want to split the string inside the GSP.
My string will look like:
ASD25785-T
I want to be able to split this into 2 strings inside the GSP view.
String a = ASD25785
String b = T
Is it possible to do that inside the GSP?
How about something like this:
<%
String[] tokens = "ASD25785-T".split("-")
String b = tokens[0]
String c = tokens[1]
%>
NB. use try catch because you may get ArrayOutofBoundException
It depends if you have a predefind format or you want something generic.
Without try/catch and using the regex find method in String:
<%
String s="ASD25785-T"
String a,b
s.find(/(.+)-(.+)/) { fullMatch, first, second -> [
a=first
b=second
}
%>
If you are certain that there will always be a match, then it is a cute one-liner:
<%
String s="ASD25785-T"
def (a,b) = s.find(/(.+)-(.+)/) { fullMatch, first, second -> [first,second]}
%>
Source:
http://naleid.com/blog/2009/04/07/groovy-161-released-with-new-find-and-findall-regexp-methods-on-string
NB: However, if you want to use it in your view, you should create a tag. Grails taglibs are almost trivial to write, and much better to use in GSP code.
http://grails.github.io/grails-doc/2.4.x/ref/Command%20Line/create-tag-lib.html
http://grails.github.io/grails-doc/latest/guide/single.html#taglibs
Here's a string manipulation taglib
class StringsTaglib {
def split = { attrs, body ->
String input= attrs.input
String regex= attrs.regex
int position= attrs.index as Integer
out << input.split(regex)[position]
}
}
you could then use it like this:
a:<g:split input="ASD25785-T" regex="-" index="0"/>
b:<g:split input="ASD25785-T" regex="-" index="1"/>
I have some question about searchable plugin :
i have two domain :
class Ads {
static searchable = true
String fromCity
String toCity
User user
static constraints = {
}
}
class User {
String username
String password
}
And i have developed my own search page with two field (fromCity,toCity) . to have something like :
def listResults = searchableService.search("NewYork","Miami")
So I would like to know how I can give to my search method this to Criteria Field.
def srchResults = searchableService.search(??????)
I'll be so grateful if someone can help me to do this.
First you need to define a searchable closure in your domain class. For instance
static searchable = {
analyzer "simple"
only = ['firstName','uuid']
firstName boost: 5.0
}
Then you can search as follow.
def searchResults = SomeDomain.search(textToSearch + "*" + " -(firstName: ${myName})", params)
-(firstName: ${myName}) this remove the my name from the search result, similarly you can and or other fields depending on your logic.
The default operator is "and" where as you can modify the operator, see following example
defaultOperator - Either "and" or "or". Default is to defer to the global Compass setting, which is "and" if not otherwise set by you.
search("mango chutney", defaultOperator: "or")
// ==> as if the query was "mango OR chutney"
// without the option it would be like "mango AND chutney"
For more detail please see the documentation.
Searchable Plugin Documentation
Let me know if you need any help.
More Help On Compass
See section 12.5.1. Query String Syntax
I would like to create a helper to return a text one character below the other. Something like that:
S
A
M
P
L
E
The purpose of this helper is to have a table with a heading of only 1 character wide. As you can see on the picture below this is ugly:
Example below looks nice:
I would like something like:
#Html.DisplayVerticalFor(x => x.MyText)
Any idea?
Thanks.
You can create an HTML helper DisplayVertical. (I am not adding the steps of how to create html helpers). The DisplayVertical will first split your text in character array and wrap each character inside a div or any other block level element, which can be inserted desired place.The implementation of DisplayVerticalFor can be something like this :
public static MvcHtmlString DisplayVertical (this HtmlHelper helper, string text)
{
string OutputString = "";
string assembleString = "<div>{0}</div>";
char[] textarr = text.ToCharArray();
foreach( char a in textarr )
{
OutputString += String.Format(assembleString, a);
}
return new MvcHtmlString(OutputString);
}
and in razor it will placed like this :
<div class="style-to-adjust-width-n-height"> #Html.DisplayVertical ("Sample") </div>
If you want to pass on a lambda expression to this html helper like this #Html.DisplayVerticalFor(x => x.MyText) then you need to add lambda expression parsing code to find out the text.
Lastly, this is a very rough code however you can add "TagBuilder" etc to make it more neat and clean.
#{int count = 0;}
#foreach (var item in Model.Resources)
{
#(count <= 3 ? Html.Raw("<div class=\"resource-row\">").ToString() : Html.Raw(""))
// some code
#(count <= 3 ? Html.Raw("</div>").ToString() : Html.Raw(""))
#(count++)
}
This code part does not compile, with the following error
Error 18 Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.Web.IHtmlString' d:\Projects\IRC2011_HG\IRC2011\Views\Home\_AllResources.cshtml 21 24 IRC2011
What I must I do?
Html.Raw() returns IHtmlString, not the ordinary string. So, you cannot write them in opposite sides of : operator. Remove that .ToString() calling
#{int count = 0;}
#foreach (var item in Model.Resources)
{
#(count <= 3 ? Html.Raw("<div class=\"resource-row\">"): Html.Raw(""))
// some code
#(count <= 3 ? Html.Raw("</div>") : Html.Raw(""))
#(count++)
}
By the way, returning IHtmlString is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString() would destroy meaning of Html.Raw()
The accepted answer is correct, but I prefer:
#{int count = 0;}
#foreach (var item in Model.Resources)
{
#Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")
// some code
#Html.Raw(count <= 3 ? "</div>" : "")
#(count++)
}
I hope this inspires someone, even though I'm late to the party.
You shouldn't be calling .ToString().
As the error message clearly states, you're writing a conditional in which one half is an IHtmlString and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.
There is never a reason to call Html.Raw(...).ToString().
Html.Raw returns an HtmlString instance that wraps the original string.
The Razor page output knows not to escape HtmlString instances.
However, calling HtmlString.ToString() just returns the original string value again; it doesn't accomplish anything.
I'm really brand new to Groovy and I'm trying to get something done. I've written some Groovy code (which works just fine) which receives some text. This text should be an integer (between 0 and 10). It may just happen a user enters something different. In that case I want to do some specific error handling.
Now I'm wondering, what's the best / grooviest way to test if a string-typed variable can be casted to an integer?
(what I want to do is either consume the integer in the string or set the outcome of my calculation to 0.
Thanks!
The String class has a isInteger() method you could use:
def toInteger (String input) {
if (input?.isInteger()) {
return input.toInteger()
}
return 0
}
use groovy contains
if ( x?.isInteger()) {
return (0..10).contains(x)
} else {
return false
}
Is this what you're saying?
Integer integer = 0
try {
integer = (Integer) string
assert integer > 0
assert integer < 10
catch(e) {
integer = 0
}
There are lots of ways this can be done in groovy, if you're comfortable with regular expressions, this is about as concise as you can get:
def processText(String text) {
text ==~ /(10|\d)/ ? text.toInteger() : 0
}
assert 0 == processText("-1")
(0..10).each {
assert it == processText("$it")
}
assert 0 == processText("11")
I'm a little unsure what you mean by "specific error handling" if the user does something different.
If this is a web application, I'd take a look at grails and the constraints that you can put on the fields of a domain object, that would let you easily express what you're trying to do.
You have the grails tag on your question, so if you are using Grails, you might consider making this an Integer property on a domain class. The param may come in as text, but you can bind it to an integer property with a default value of 0:
class MyDomain {
Integer whatever = 0
static constraints = {
whatever( min:0, max:10)
}
}