CSS in Play Framework 2.0.3

2019-08-01 12:38发布

I'm having some problems using CSS in Play Framework 2.0.3, and was wondering if anyone could spot the mistakes I am making.

I have a view called siteview.scala.html, defined as:

@(name: String, records: List[Record])

@import helper._

@main(name) {
<html>
    <head>
    <link rel="stylesheet" type="text/css" href="@routes.Assets.at("stylesheets/main.css")">
    </head> 
    <h1>@name</h1>

    <ul>
          ...
    </ul>
</html>
}

I have a CSS file defined as main.less in app/assets/stylesheets which looks like:

h1 {color:#F6F9ED;}

@font-face {
    font-family: Gentium;
    src: url(fonts/GenBasR.ttf);
}
font-family: Gentium, Arial, Georgia;

Apologies for the terrible style, I kept changing to try and make it do something! The route to the assets has been left as the default.

Play definitely compiles the CSS; if there is a syntax error, it is spotted. However, the CSS is just not being loaded into the HTML.

I tried copying the CSS file right into the public folder, but that gave me a duplicate file error from the compiler, which probably indicates the file is being put in the right place.

How do I make the HTML display with styling? I have a feeling I am missing something quite obvious, but am quite new to web development so I'm quite out of ideas.

2条回答
贪生不怕死
2楼-- · 2019-08-01 13:29

The solution provided by @biesor didn't work for me. I've added this line in routes file:

GET     /stylesheets/*file          @controllers.Assets.at(path="/public/stylesheets", file)

Then I've included the css file in my html page in this way:

<link rel="stylesheet" media="screen" href="/stylesheets/core.css">

I think that this isn't the best way to include a css file but I cannot find another solution.

查看更多
可以哭但决不认输i
3楼-- · 2019-08-01 13:32

I think that default approach can be confusing for both: developer and Play, so I'd suggest renaming the folder app/assets/stylesheets to app/assets/less (or something else, in general make sure, you haven't the folder with the same name in /public). Thanks to this you can be always sure that you're using LESS or static asset, as you just can see the difference in paths:

<!-- resolves to '/public/less/main.css' or (main.min.css) 
                                                   from app/assets/less folder -->
<link rel="stylesheet" type="text/css" 
                       href='@routes.Assets.at("less/main.min.css")'>

<!-- resolves to '/public/stylesheets/main.css' from 'public/stylesheets' folder -->
<link rel="stylesheet" type="text/css" 
                       href='@routes.Assets.at("stylesheets/main.css")'>

route stays untouched:

GET     /public/*file      controllers.Assets.at(path="/public", file)
查看更多
登录 后发表回答