Should we remove HTML attributes while using Thymeleaf?

Tags: java thymeleaf
By : DimaSan
Source: Stackoverflow.com
Question!

I'm studying Thymeleaf and have found out that in almost all examples there are Thymeleaf's tag values as well as standard HTML values like:

<title th:text="#{product.page.title}">Page Title</title>

<link href="../static/css/bootstrap-3.3.7-dist/bootstrap.min.css" rel="stylesheet"
      th:href="@{/css/bootstrap-3.3.7-dist/bootstrap.css}"/>

<script src="../static/js/jquery-3.1.1.js"
        th:src="@{/js/jquery-3.1.1.js}"></script>

These standard tag values like Page Title or href="../static/css/bootstrap-3.3.7-dist/bootstrap.min.css" etc. are ignoring by controller and don't rendering on the page.

I'm wondering – is it just a good practice to leave them to improve code readability or it is better to remove them to clean up code?

Because for the compiler they are useless and have not any affect to the rendering result.

By : DimaSan


Answers

This depends entirely on your development process.

You could keep the HTML attributes around in the early phases, while you are still trying to lay out the page using just your browser.

But, once you get to a point where you are using automated unit / web testing, you can safely remove the HTML attributes because this testing should always be using a prod-like environment (which would include thymeleaf).

By : Jason


The thing with lazy views is that the underlying iterator is not evaluated till some consumer consumes it. And map, flatMap etc are not consumers, they are transformer which transform a lazy view into another lazy view.

Consumers include foreach, fold etc. Only when consumers consume the view, the actual transformation steps will be performed. So you just have to wrap your consume call in a Try

val v = (1 to 10).view.map {
  case 5 => throw new Exception("foo")
  case v => v
}

val w = v.map(_ + 10)

Try(w.foreach(i =>
  println(i)
)) match {
  case Success(_) => println("Successfully done.")
  case Failure(ex) => println("I tried so hard... but it doesn't even matter")
}

And... the thing with Try is that, you are supposed to wrap problem creators with it so that it guards any possible exceptions. So what you should actually do is to wrap your transform with a Try.

val view1 = (1 to 10).view

val view2 = view1.map(v => Try(v match {
  case 5 => throw new Exception("foo")
  case v => v
}))

// Now, your view2 is actually a view of Try's

// you can map it to transform again

val view3 = view2.map({
  case Success(v) => v + 20
  case Failure(ex) => throw ex
})

// now consume

view3.foreach({
  case Success(v) => println(v)
  case Failure(ex) => println("this one is a bad boy")
})


This video can help you solving your question :)
By: admin