Grails - Language prefix in url mappings

放肆的年华 提交于 2019-12-01 14:10:09

The biggest problem you have to deal with is having no prefix for English. Most of your mapping seems totally ok. I would recommend you to work with named mappings.

But first I would recommend you to work with filters for setting a language parameter for every user.

def filters = {
    languageCheck(controller: '*', action: '*') {
        before = {
            if( params.lang == null) {
                redirect( controller: params.controller, action: params.action, params:[ "lang": request.locale.language.toString() ] + params )
            }
        }
    }
}

If a user with missing language parameter enters your site the language is set by the filter and he is redirected to the controller with language parameter. Be careful if you are using a security framework which is also redirecting. You can only redirect once. In that case you have to exclude those urls or controllers from the filter.

Now we will look at your mapping problem. Since Grails 1.2 there are so called Named URL Mappings. E.g.

name storeCategory: "/$lang/store/$category" {
        controller = "storeItem"
        action = "index"
        constraints {
            lang(matches:/pl|en/)
        }
    }

Inside your GSP you can refer to your named mapping with

<g:link mapping="storeCategory" params="[lang:'en', category:'new']">Category</g:link>

This should solve your problem. You can find all about named mappings in the Grails Reference

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!