Grails找不到我的资源

时间:2014-11-12 10:40:17

标签: css grails gsp url-mapping

我的Grails项目结构:

my-app/
    grails-app/
        <mostly typical grails-app structure>
        views/
            web/
                index.gsp
            app/
            admin/
            layouts/
                main.gsp
    <rest of project structure is like any other Grails app>

所以你可以看到,通常,索引页面位于grails-app/views/index.gsp,我在grails-app/views/web/index.gsp处。

我的application.properties

app.grails.version=2.4.2
app.name=my-app
app.context=/
app.version=0.1

我的UrlMappings.groovy的一部分:

"/"(view:"/web/index")

我的main.gsp布局:

<!DOCTYPE html>
<html lang="en">
<head>
    <title><g:layoutTitle default="MyApp"/></title>
    <g:resource dir="css" file="myapp.css" />
    <g:layoutHead/> 
</head>
<body>
    <g:layoutBody/>
    <g:resource dir="js" file="myapp.js" />
</body>
</html>

我的index.gsp

<!DOCTYPE html>
<html>
<head>
    <meta name="layout" content="main"/>
</head>
<body>
    <h1>Hello!</h1>
</body>
</html>

当应用程序启动并在浏览器中查看时,很明显找不到myapp.css,因为页面样式完全错误。当我查看页面源时,我看到:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>MyApp</title>

    /css/myapp.css
    <meta name="layout" content="main"/>
</head>
<body>
    <h1>Hello!</h1>
    /js/myapp.js
</body>
</html>

因此,听起来Grails会使用您的app.context并将其用作所有资源的前缀。由于我没有正确连接,Grails只是将我的<g:resource>标签翻译成纯文本并在HTML中打印出来。

我想我的问题是:我需要做什么才能让Grails找到我的CSS / JS资源?

2 个答案:

答案 0 :(得分:4)

我不确定标记到标记中是否可以正常工作,所以这样写:

<link rel="stylesheet" href="${resource(dir:'css', file:'myapp.css')}" charset="utf-8"/>

答案 1 :(得分:2)

根据Documentation,resources标签生成一个链接(URI)字符串。可用于href,JavaScript,Ajax调用等。

使用脚本或链接标记内的资源标记来获取页面中加载的css / js,

<link rel="stylesheet" href="<g:resource dir="css" file="myapp.css" />" charset="utf-8"/>

你也可以使用resources plugin,我会推荐它,因为它解决了目的并且有良好的documentation