I'm attempting to serve a CSS file through my url.py file so I can use template tags in my CSS.
Here's my code.
Base.html:
<head>
...
<link rel="stylesheet" type="text/css" href="/site_media/css/wideTitle.css" />
urls.py:
(r'^site_media/css/wideTitle.css','lightbearers.views.viewWideTitle'),
views.py:
def viewWideTitle(request):
contentListAbout = About.objects.filter(Q(startDate__lte=datetime.now())).order_by('-startDate')
if len(contentListAbout) > 0:
contentAbout = contentListAbout[0]
else:
contentAbout = None
...
return render_to_response('wideTitle.css', {'contentAbout':contentAbout, ...},
context_instance=RequestContext(request))
settings.py:
TEMPLATE_DIRS = (
os.path.join(PROJECT_PARENT, "templates"),
os.path.join(PROJECT_PARENT, "media/css"),
)
wideTitle.css (in /media/css):
#wideTitle{
clear:both;
height:180px;
padding-left:0px;
background: url({{ contentAbout.headerImage.url }}) no-repeat top left;
}
I can access the CSS file by entering its URL in my browser, but the Base.html isn't reading it at all. I think I've got everything decent; I've looked here and here for tips. Anyone have ideas?
Is the generated stylesheet being served with the correct mime type? If not, the browser might not interpret it as CSS.
I can’t remember if render_to_response accepts content_type='text/css as an argument, but there is a way to set it if Django isn’t already using the correct mime type.
Edit: as #TommasoBarbugli pointed out, you want the mimetype argument for render_to_response.
(Firefox’s Firebug add-on, or the Web Inspector in Chrome/Safari, should be able to show you the stylesheet’s mime type.)
Related
Is debugging sourceURL possible for CSS in Firefox?
The solutions listed in the following do not appear to work:
//# sourceURL equivalent for CSS
Is there something like source maps for CSS?
MDN in Style Editor states a possibility but it seems to be for Sass.
Update on reply
Using sourceMappingURL & sourceURL has some incomplete result:
Inspector still shows file as blob ❎
blob:moz-extension://*****-****-******/*****-****-******
Style Editor lists file name ✅
Style Editor fails to display file (since there is no real URL) ❎
Error while fetching an original source: NetworkError when attempting to fetch resource.
Source URL: moz-extension://*****-****-******/****.css
I didn't find a solution with sourceURL. I used an empty inline source mapping as an alternative. "Empty" meaning that it does not contain any source changes, it just points at the source file.
The source mapping with /*# sourceMappingURL={sourcemapurl} */ in Firefox will behave almost like /*# sourceURL={url}*/ in Chrome.
It guess it depends on your use case if that is an option.
In my case the code looks like this (uses magic-string for generating the source mapping):
function addStyle (filename, css) {
const sourceMap = new MagicString(css).generateMap({
source: filename
})
css += '\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */'
css += '\n/*# sourceURL=' + sourceMap.sources[0] + ' */'
document.head.appendChild(document.createElement('style')).innerHTML = css
}
addStyle('https://cvzi.github.io/stackoverflow/65274147/mystyle.css', `body{
font-family:sans-serif;
color:black;
background:green;
}
body h1{
color:white;
size:15;
}
`)
<script src="https://unpkg.com/magic-string#0.25.7/dist/magic-string.umd.js"></script>
<h1>This is h1</h1>
This question already has answers here:
How do I serve CSS and JS in Go
(2 answers)
Closed 4 years ago.
I just started learning go and 1 of the things I really wanna learn to do is making sites in go. I watched some tutorials for it and making sites worked, but I didn't know how to add styles.
I searched for some examples on the internet and stackoverflow, but couldn't find one that actually worked for me (and stayed simple).
Underneath is the code that I ended up with.
But I think I got a new problem now cause in the console it says:
I tried a lot of solutions that I found on the internet for this but none of them worked so I am pretty sure it is because I imported the css wrongly in go.
Go (functions.go):
package main
import (
"html/template"
"net/http"
)
type IndexPage struct {
Title string
SubTitle string
}
func indexHandler(w http.ResponseWriter, r *http.Request){
p := IndexPage{Title: "Pizza site", SubTitle: "everyone loves pizzas"}
t, _ := template.ParseFiles("index.html")
t.Execute(w,p)
}
func main() {
http.HandleFunc("/", indexHandler)
http.Handle("/css/", http.FileServer(http.Dir("css")))
http.ListenAndServe(":8080", nil)
}
Html (index.html):
<html lang="nl">
<head>
<meta charset="utf-8">
<title>Pizzaaaaaaa</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<article>
<h1>
{{ .Title }}
<span class="subtitle">{{ .SubTitle }}</span>
</h1>
<p>Some text</p>
</article>
</body>
</html>
CSS ( /css/style.css )
*{
color: rgb(250, 157, 157);
}
FileTree
Your handle return 404 when you try to access css file from this url: /css/*
Change your css handle with this:
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./css"))))
*You got 'text/plain' because the 404 is a plain text.
You have to add the mime type for css files in your response header.
if strings.HasSuffix(path, ".css") {
w.Header().Add("Content-Type", "text/css")
}
Or something similar with a variable for multiple different mime types.
EDIT:
Please also check this go lang package to include for better mime type handling:
https://golang.org/pkg/mime/
I have an HTML document that uses multiple style tags. One of those styles has the following content
<style id='pstyle'>
.p0010, .p0016, .p0022, .p0028, .p0032,
.p0034, .p0038, .p0042, .p0044, .p0046,
.p0048, .p0050, .p0052, .p0054, .p0056,
{
max-width:100%;
background-size:100%;
background-image: url('sprites.png');
}
</style>
document.styleSheets allows me to access the full set of stylesheets used by the document. From there - once I have grabbed the right stylesheet - I can use the cssRules array attribute to access the selectorText attribute of each contained style. However, I have been unable to figure out how to find the "right" style sheet. Whilst I can give the stylesheet an id this does not turn up as an attribute of the document.styleSheets[n] object.
I do a great deal of DOM manipulation but it is mostly with the visual elements in the document. I'd be much obliged to anyone who can tell me how I go about identifying the "right" stylesheet
A plain English version of the task
a. Find the style element - bearing in mind that there will be others - with the id pstyle
b. Read the class names defined therein and do whatever
I'm not sure to understand if you want to get the stylesheet associated with the <style> element, or if you want to retrieve the element from the stylesheet.
So here you'll get both :
// from the element
console.log(pstyle.sheet === document.styleSheets[2]);
// from the stylesheet
console.log(document.styleSheets[2].ownerNode === pstyle);
<style id='pstyle'>
</style>
note that in the snippet it's [2] because stacksnippet does inject stylesheets
And now to get the cssRules and selectorText, you just have to read it from the selected styleSheet:
var pstyle = document.getElementById('pstyle');
// from the element
console.log(pstyle.sheet.cssRules[0].selectorText);
// from the stylesheets
for(var sheet of document.styleSheets){
if(sheet.ownerNode === pstyle){
console.log(sheet.cssRules[0].selectorText);
}
}
<style id='pstyle'>
.p0010, .p0016, .p0022, .p0028, .p0032,
.p0034, .p0038, .p0042, .p0044, .p0046,
.p0048, .p0050, .p0052, .p0054, .p0056
{
max-width:100%;
background-size:100%;
background-image: url('sprites.png');
}
</style>
I have a background image that I can not get to stay just on one page. I have made a welcome controller with one home view to display it. I am precompiling my assets as well. The background shows up just fine, but my goal is to just show the background image on my home.html.erb view.
welcome/home.html.erb:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<%= I18n.locale || 'en' %>"
lang="<%= I18n.locale || 'en'%>">
<body class="container">
<h1>title</h1>
</body>
</html>
welcome controller:
class WelcomeController < ApplicationController
def home
end
end
stylesheets/welcome.css.scss:
body
{
background: {
image: asset-url("image.jpg");
}
}
and I have the following in my application layout:
<head>
<%= stylesheet_link_tag "welcome" if controller_name == "welcome" %>
</head>
and in config/initializers/assets.rb :
Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.precompile += %w( welcome.css )
Add specific css,
body.welcome
{
background: {
image: asset-url("image.jpg");
}
}
and in html,
<body class="container welcome">
You must be wondering even though you have not included specific file then why it is applying all over. This is because you must have specified require_tree . in application.css
In Rails:
Try creating a css class for the background image
.splash {
background-image: image-url("image.jpeg");
background-size: cover;
background-position: center;
background-attachment: fixed;
}
If you want all pages to display the image
<html class="splash"> ... </html>
But on one page only, on that view page, wrap everything in
<body class="splash"> ... </body>
You are overriding body for the entire application. Make a class instead and call it using div on the page you want to display the background image.
Also, you are calling the use of the stylesheet from the application layout rather than the page itself.
Stylesheet
#app/views/layouts/application.html.erb
<head>
<%= stylesheet_link_tag controller_name if controller_name == "welcome" && action_name == "home" %>
</head>
#app/assets/stylesheets/welcome.css.scss
body {
background: {
image: asset_url("image.png");
}
}
#config/application.rb
config.assets.precompile += %w(welcome.css)
This should load the welcome stylesheet if you're visiting the welcome#home view. I would strongly recommend against using classes to determine this page - it's far cleaner to include a stylesheet, as this will give you scope to extend the functionality as you wish
--
Test
To test this, you should first look at whether your welcome.css is being loaded when you hit the welcome#home view. To do this, you just need to right-click > view-source.
If the stylesheet is present, you'll want to ensure your styling is performing correctly. This will be trickier to debug, but will just entail you looking at the loaded CSS file & seeing what it's doing with the elements on your page.
If you do the above, comment as to whether you're seeing the welcome.css in your source. If you are, it's a good sign, and we'll be able to look at the CSS after that
Your welcome.css file is being included by the asset pipeline so will apply the background on every page. In order to apply the background image to the body only on the home page, you need to apply a class to the body when the home page displays.
However, if you are correctly using layouts, the opening <body> tag will be in your application.html.erb or in a partial so not available in your home.html.erb. You will need it to add it dynamically so I suggest you use a small jQuery script at the end of your home template.
<script>$('body').addClass('home-page');</script>
Then you can amend your CSS to
body.home-page {
background: {
image: asset-url("image.jpg");
}
}
That should give you the results you require.
We have couple of portlets deployed on Websphere Portal Server. In the css file we have included a behavior attribute for img tag.
img {
position:relative;
border:none;
outline:none;
behavior: expression((this.runtimeStyle.behavior="none")&&(this.pngSet?this.pngSet=true:(this.nodeName == "IMG" && this.src.toLowerCase().indexOf('.png')>-1?(this.runtimeStyle.backgroundImage = "none", this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "', sizingMethod='image')", this.src = "transparent.gif"):(this.origBg = this.origBg? this.origBg :this.currentStyle.backgroundImage.toString().replace('url("', '').replace('")', ''), this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.origBg + "', sizingMethod='crop')", this.runtimeStyle.backgroundImage = "none")), this.pngSet=true) );
}
We have figured out that this behavior tag is resulting in multiple HTTP requests.In one of the Portlet JSP, we have included a style class as follows
<link rel="stylesheet" type="text/css" title="Style"
href=''<%=request.getContextPath()+"/theme/stylesheet.css" %>'>
The issue is there only when we have that request.getContextPath(). If I substitute that with the actual context root, it is not giving the problem. Can someone please let me know why that behavior attribute is causing the problem?
Yahoo! has an article with the title Best Practices for Speeding Up Your Web Site. One thing that is to be avoided is expressions in CSS as they are evaluated a bit more often than expected, just by moving the mouse or scrolling the page.
The article can be read here and look for the heading Avoid CSS Expressions:
http://developer.yahoo.com/performance/rules.html