twirl
twirl copied to clipboard
Support for variables
I've seen there was another issue for this (#63) but it's closed and I think it's an important lack.
For now, if we need to declare some variables we have to to this:
@defining(
myObject.calcFoo,
myObject.calcBar
) { case (foo, bar) =>
@defining(myObject.calcResult(foo, bar)) { result =>
… the whole template …
}
}
And it's not handy. However, we can declare reusable blocks:
@foo = @{myObject.calcFoo}
@bar = @{myObject.calcBar}
@result = @{myObject.calcResult(foo, bar)}
But they are treated as functions, so foo
, bar
and result
will be recalculated every time. I think every time a reusable block is declared without parenthesis, its value should be calculated once and use it as a variable. So the previous example would define variables, and the following one would define functions.
@foo() = @{myObject.calcFoo}
@bar() = @{myObject.calcBar}
@result() = @{myObject.calcResult(foo, bar)}
@adrianhurt I like the idea in general, but how would this effect already written templates?
Yeah, I know… But it wouldn't be the first time the backward compatibility is broken. I think it's more logic. Anyway, in my opinion it would be nice to add a note in Play's doc warning that @foo = @{…}
is a function. In my case I realized it months later that I was recalculating several time the same value.
There would be more options to write the same thing if the problem is to maintain the backward compatibility:
@foo = (myObject.callcFoo) // Html
@foo = @(myObject.callcFoo) // Scala value
@foo = {{myObject.callcFoo}} // Html
@foo = @{{myObject.callcFoo}} // Scala value
...
I assume you mean we should support defining immutable values, but not mutable variables.
I believe it's typical scala style to omit parens only for pure functions that are side-effect free. This is what I would typically do at least. So if users are doing that here, @adrianhurt's suggestion should not cause too many backwards compatibility issues. I'm not sure what most code in the wild looks like though.