Rythm template engine define custom method in Java code

221 views Asked by At

I know there is the possibility to define a method in templates like this:

@def myMethod(String parameter){
     before @parameter after 
}

and use it:

@myMethod("my object")

This will output: before my object after Can I define the myMethod in Java code and use it in multiple templates ?

1

There are 1 answers

0
Gelin Luo On BEST ANSWER

You don't need to define that method in Java code. Instead in your rythm template home directory create a file named __global.rythm, and define that method there, then all your rythm template will automatically pick up that method because __global.rythm will be @include by Rythm engine in every template automatically. Below is a real global rythm file from my project:

@import com.abc.model.*
@import org.rythmengine.spring.web.Csrf
@import org.rythmengine.RythmEngine
@import com.abc.AppConfig
@import com.abc.model.color.*;
@args Csrf csrf


@def String csrfParam() {
  return "__csrf=" + ((null == csrf) ? "nocsrf" : csrf.value);
}

@def RythmEngine rythm() {
  return __engine();
}

@def User me() {
  return User.me();
}

@def boolean loggedIn() {
  return User.me() != null;
}

@def String host() {
  return com.abc.AppConfig.host()
}