'Language prefix in url mappings not working in every condition
I'm having problem with language mappings. The way I want it to work is that language is encoded in the URL like /appname/de/mycontroller/whatever
If you go to /appname/mycontroller/action it should check your session and if there is no session pick language based on browser preference and redirect to the language prefixed site. If you have session then it will display English. English does not have en prefix (to make it harder).
So I created mappings like this:
class UrlMappings {
static mappings = {
"/$lang/$controller/$action?/$id?"{
constraints {
lang(matches:/pl|en/)
}
}
"/$lang/store/$category" {
controller = "storeItem"
action = "index"
constraints {
lang(matches:/pl|en/)
}
}
"/$lang/store" {
controller = "storeItem"
action = "index"
constraints {
lang(matches:/pl|en/)
}
}
"/$controller/$action?/$id?"{
lang="en"
constraints {
}
}
"/store/$category" {
lang="en"
controller = "storeItem"
action = "index"
}
"/store" {
lang="en"
controller = "storeItem"
action = "index"
}
"/"(view:"/index")
"500"(view:'/error')
}
}
It's not fully working and langs are hardcoded just for now. I think I did something wrong. Some of the reverse mappings work but some don't add language.
If I use link tag and pass params:[lang:'pl'] then it works but if I add params:[lang:'pl', page:2] then it does not. In the second case both lang and page number become parameters in the query string. What is worse they don't affect the locale so page shows in English.
Can anyone please point me to the documentation what are the rules of reverse mappings or even better how to implement such language prefix in a good way?
Solution 1:[1]
I'd like to add this: if you're having additional params that should be appended using ?param=value, you'll be in trouble if you don't explicitly add them to your URL mappings. This is because the URL mapping resolver respects the controller and action parameter as parameters with a special meaning and will only match mappings that have the exact same set of parameters for generating links.
However, when you're using pagination, you will be getting trouble.
So in addition to the above, do the following:
class LangAwareUrlMappingsHolderFactoryBean extends UrlMappingsHolderFactoryBean {
@Override
public UrlMappingsHolder getObject() throws Exception {
def obj = super.object
obj.DEFAULT_CONTROLLER_PARAMS = [UrlMapping.CONTROLLER, UrlMapping.ACTION, "lang"] as Set
obj
}
}
And adjust the resources.groovy:
"org.grails.internal.URL_MAPPINGS_HOLDER"(LangAwareUrlMappingsHolderFactoryBean) { bean ->
bean.lazyInit = true
}
And you'll get
/en/controller/action?offset=10
instead of
/controller/action?offset=10&lang=en
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fabiangebert |
