简体   繁体   English

覆盖grails g:链接标记

[英]override grails g:link tag

I am trying to override the g:link tag so that I can prefix an extra string. 我试图覆盖g:link标记,以便我可以为额外的字符串添加前缀。 Here is my code: 这是我的代码:

import org.codehaus.groovy.grails.plugins.web.taglib.*

class ApplicationTagLib {

    static namespace = "g"

    def link = { attrs, body ->
        if("es".equalsIgnoreCase(request.stLocale.language)) {
            attrs['controller'] = "es/" + attrs['controller']
        }
        def applicationTagLib = grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')
        applicationTagLib.link.call(attrs, body)
    }
}

This works fine except for when I add "es/" the resulting path gets translated into es%2F instead of es/ which causes the link to not work. 这工作正常,除了当我添加“es /”时,生成的路径被转换为es%2F而不是es /,这导致链接不起作用。

Is there a way to prevent this from automatically encoding the new slash or a better way to prefix this string to the controller path? 有没有办法防止这种情况自动编码新的斜杠或更好的方法将此字符串作为前缀添加到控制器路径?

You should be aware that in Grails the controller package (thus it's location in the project's structure path) does not correlate with the default URL mapping - the structure is flattened. 您应该知道,在Grails中,控制器包(因此它在项目结构路径中的位置)与默认URL映射不相关 - 结构被展平。

The slash you add to the controller name is thus encoded as it would otherwise form a part of the URL (and thus not map to a controller). 因此,您添加到控制器名称的斜杠将被编码,否则它将构成URL的一部分(因此不会映射到控制器)。

Perhaps the logic for handling different locale be better placed in a controller anyway. 也许处理不同语言环境的逻辑最好放在控制器中。

You can add this '/es' prefix in all links generated by grails tags by configuring your UrlMappings.groovy. 您可以通过配置UrlMappings.groovy在Grails标记生成的所有链接中添加此“/ es”前缀。 If you're using the default one, generated by grails create-app command, you can add '/es' in your URL's like this: 如果你使用的是由grails create-app命令生成的默认值,你可以在你的URL中添加'/ es',如下所示:

class UrlMappings {

    static mappings = {
        "/es/$controller/$action?/$id?" {  // <---------- added '/es' prefix
            constraints {
                // apply constraints here
            }
        }

        "/"(view: "/index")
        "500"(view: '/error')
    }
}

To learn more about URL Mappings, see the Grails guide . 要了解有关URL映射的更多信息,请参阅Grails指南

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM