Style.css imported with GO gives a MIME error [duplicate] - css

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/

Related

how to import image base64 in css

Is it possible to somehow import the image base64 from another file? or save the url to a variable and import it to CSS? since the code is very long and it does not seem clean in this way.
Thank you for your help guys.
index.css
.column {
margin: calc(var(--grid) / 2);
border: var(--borderWidth) solid #fffddd;
border-radius: var(--borderRadius);
background-image: linear-gradient(rgba(0, 0, 0, 0.769),rgba(0, 0, 0, 0.961)),url('data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QDWRXhpZgAATU0AKgAAAAgABAEPAAIAAAASAAAAPgEQAAIAAAAMAAAAUIKaAAUAAAABAAAAXIdpAAQAAAABAAAAZAAAAABOSUtPTiBDT1JQT1JBVElPTgBOSUtPTiBENTEwMAAAAAAKAAAMgAAFgpoABQAAAAEAAACigp0ABQAAAAEAAACqiCcAAwAAAAICgAAAkAMAAgAAABQAAACykgoABQAAAAEAA...
What you could do is to use var() CSS from inside another CSS file that you can import .
File myCssVar.css
:root {
--mybguri64: url(data-image/jpeg;base64, ... ) ;
}
Your CSS file
#import url(myCssVar.css);
.column {
background-image: linear-gradient( ....), var(--mybguri64) ... ;
}
It will make your CSS easier to read.
Looks like from your edit you almost had it .
Background-image's URL is a string value. Of course, you can store it in another file, import it and use js to inject it dynamically.
The best solution to that is to use the server side script with an inline css to make this happen. to make this happen. lets say the backend language is php. and your pages are made up of 3 templates components. It could be in different backend languages either ASP.net, Javs, php, node... but i'm using php here since i'm vast in it. just follow through its quite simple and direct.
base64ImageFile.php - the file with the base64image variable it could be more than 1
header_template.php
footer_template.php
application.php
then in your base64Images.php you have this there..
<?php
$base64Img ='data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7';
$base64Image2 = 'data:image/png;base64,sgw....';
$base64Image3 = 'data:image/png;base64,sgw....';
$base64Image4 = 'data:image/png;base64,sgw....';
?>
**in my header_template.php, add the template to the beginning of the file.. **
<?php
require('base64images.php'); //the images are rendered here..
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
li {
background:url(<?php echo $base64Img; ?>) <!-- and used here --->
no-repeat
left center;
padding: 5px 0 5px 25px;
}
</style>
</head>
in my footer_template.php
<!--- footer elements/scripts go here --->
<script src="...."></script>
<script src="..."></script>
</html>
application.php - file, merge template components to build page here
<?php require('header_template.php'); ?>
<body>
.......body content coes here...
</body>
<?php require('footer_template.php'); ?>
this way you can re-use and seperate the components and even seperate images into different files and call them. in your file instead of typing it out. or even multiple images... but the CSS must be inline with the HTML..

Can't get external style sheets to work with golang templates

Internal CSS works fine but external style sheet isn't working. I end up with the standard page with no styling showing up. The templates served just fine except no CSS.
Created a simple app to eliminate some of the variables but the same issue persists.
root of app
C:\workspace\goworkspace\src\practice3\
GOPATH C:\workspace\goworkspace
//practice3/main.go
package main
import (
"log"
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("static"))
http.Handle("/", fs)
log.Println("Listening...")
http.ListenAndServe(":8080", nil)
}
//practice3/static/example.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>A static page</title>
<link rel="stylesheet" href="/stylesheets/main.css">
</head>
<body>
<h1>Hello from a static page</h1>
</body>
</html>
//practice3/stylesheets/main.css
body {
background-color: lightblue;
}
h1 {
color: navy;`enter code here`
margin-left: 20px;
}
No errors, everything seems to work fine (including internal css) except for the external css.

How to display a leaflet map in a single post in jekyll?

I'm trying to insert a map in a single post in Jekyll.
Here is the visible effort of my attempt to this: github link
Here is the link to the github's account itself: link
I took a default template, ie Hyde.
Then I added the Leaflet's CSS and JS files in the _includes/head.html
Then I created a post that relied on the _layouts/default.html (default draws from head.html)
As I said, I'm attempting to insert a single map in a single post. If you look at the first link, it shows the map all over the blog in a weird manner.
It doesn't show up in the single post itself.
How can I make this work?
I'm hoping to eventually have a series of posts each with their own map, if that's possible.
Here is the code in the solitary post that I have up so far:
---
layout: default
title: Trying to integrate map in jekyll
---
<div id="map">
</div>
<script>
var map = L.map('map').setView([34.00000, -118.260126], 14);
mapLink =
'OpenStreetMap'; L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: 'Map data © ' + mapLink, maxZoom: 18, }).addTo(map);
var marker = L.marker([34.063298, -118.260126]) .addTo(map).bindPopup("<b>Blah Blah Blah</b><br /><a href='http://www.cnn.com'>Additional Information</a><br />").openPopup();
</script>
I realize that this post relies a lot on links, and that's frowned up on here at SO. But I have no other way of explaining my problem.
Correct code in _includes/head.html is :
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css">
not
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css"></script>
and
<style type="text/css">
#map {
width:400px;
height:550px;
background-color: red;
}
</style>
not
<style type="text/css">
#map {
width:400px%;
height:550px;
background-color: red;
}
</style>

Using template language in CSS files correctly

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.)

inline Problem adding custom style_format to tinymce

I'm trying to add a custom style in the style menu.
style_formats : [
{title:'Estilos'},
{title : 'Bold text', inline : 'b'},
{title : 'Blue text', inline : 'span', styles : {color : '#006'}},
{title : 'Blue header', block : 'h1', styles : {color : '#006'}},
/*this one*/ {title : 'Codigo fuente', inline : 'code', classes : 'prettyprint', exact: true}
],
Basically i want selected text to turn in:
<code class="prettyprint">
codeline1
codeline2
codeline3
</code>
But i get:
<code class="prettyprint"> codeline1</code>
<code class="prettyprint"> codeline2</code>
<code class="prettyprint"> codeline3 </code>
How can i make to all selection to be inserted in same <code></code> ??
tried also: {title : 'Codigo fuente', block : 'code', classes : 'prettyprint', exact: true}
And i get same result but just with no blank spaces or \n
If you want to see why i'm asking this
Thanks!
I've been working on this on and off for a few days and still cannot get a fully working solution. I think it's close but I just don't have any more time to spend on it. It also seems to be rather hacky, so I have to ask if there is not just a more simple way to do this, that is, does it really need TinyMCE? Might be easier to just use a <textarea> and prettify.
I also used a bit of advice from this other question: Remove styles when pasting from Word or other source
The idea I was experimenting with was to manipulate the TinyMCE content if the code was "prettified" so that editing occurs on the raw text rather than the prettified version. So I have hooked into the TinyMCE onchange and onKeyDown callbacks to switch the content back to an unpretty version. The only problem is that the first keypress will not register as it is swallowed by the act of replacing the content. There is a way to Programmatically sending keys to input field? but it is not supported in Webkit!
Also, there seems to be some bugs, as it still adds multiples <code> elements if code is typed directly into the TinyMCE. However, pasting code and then editing seems to work OK.
So if you type code and then apply the "Source Code" style. all the carriage returns are removed (probably same issue as #András identified).
So here is my partial solution:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
pre {
width:500px;
}
code {
white-space:pre;
line-height:1;
margin:0;
padding:0;
}
#pretty {
display:block;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
<link type="text/css" rel="stylesheet" href="prettify/prettify.css" />
<script type="text/javascript" src="prettify/prettify.js"></script> <!-- from http://code.google.com/p/google-code-prettify/ -->
<script type="text/javascript">
var plainContent = null;
function applyPrettyPrint(inst) {
if (tinyMCE.activeEditor.isDirty()) {
var content = tinyMCE.activeEditor.getContent({format : 'raw'});
if (content.indexOf('prettyprint') > 0) {
$('#pretty').html(content);
prettyPrint();
tinyMCE.activeEditor.setContent($('#pretty').html(), {format : 'raw'});
} else {
plainContent = content;
}
}
}
tinyMCE.init({
// General options
mode:'textareas',
theme:'advanced',
forced_root_block:false,
force_br_newlines:true,
force_p_newlines:false,
content_css:'prettify/prettify.css',
// http://tinymce.moxiecode.com/wiki.php/Plugin:paste
plugins:'paste',
onchange_callback:'applyPrettyPrint',
setup:function(ed) {
ed.onKeyDown.add(function(ed, e) {
if (ed.getContent().indexOf('prettyprint') > 0) {
ed.setContent(plainContent, {format : 'raw'});
}
});
},
style_formats:[
{title : 'Source Code', block : 'code', classes : 'prettyprint', exact: true}
]
});
</script>
</head>
<body>
<form method="post" action="somepage">
<div><textarea name="content" cols="50" rows="15"></textarea></div>
</form>
<p id="pretty" ></p>
<p>Plain code to copy inside textarea</p>
<pre>
class Foo {
private int bar = 0;
public doSomething() {
return bar;
}
}
class Foo { private int bar = 0; public doSomething() { return bar; } }
</pre>
</body>
</html>
Note: You will need to download TinyMCE and prettify and make sure the paths to the .js and .css resources are correct for this to work.
Hope it helps!
Well I only have a partial answer, but it still might help you a bit. From what I gather, you'd like to be able to type or paste some code into the tinyMCE text area (and not the raw html code of the editor field), and then apply some styles to that block afterwards, so it will be prettified.
(As a sidenote, I think anyone who qualifies adding a code block to a richt text editor field, should be able to press the "raw html" button, paste his code, and wrap it into a <pre> or <code> tag. Especially if you add a bit of instruction on what to do, just above or below the editor area. And then you'd be home free. And everyone does it this way.)
Nonetheless, going back to the original problem. If you enter lines of codes into the tinyMCE textarea, upon each enter pressed you'll get your line wrapped into a <p> tag.
So if you type:
if (this_is_the_best_line_ever == true) { ... }
and press enter, you'll get
<p>if (this_is_the_best_line_ever == true) { ... }</p>
So, using your example, you would never actually see this
<code class="prettyprint">
codeline1
codeline2
codeline3
</code>
but rather this
<code class="prettyprint">
<p>codeline1</p>
<p>codeline2</p>
<p>codeline3</p>
</code>
The problem with the latter, that it is not valid HTML, never was, never will be, and tinyMCE rightfully will not produce that code. Reason being <pre> and <code> are inline elements, and <p> being block level element, hence <pre> and <code> can not contain any <p>s.
We're getting to the answer (even if it's only half an answer), so don't give up.
Best approach would be to use <div> wrappers around your code block. This is legal, tinyMCE will happily do it for you, see below (note the wrapper attribute!):
style_formats : [
{title : 'Codigo fuente', block : 'div', classes : 'prettyprint', wrapper: 1}
]
We could start celebrating right now, but your chosen plugin, the code prettifier, only processes <pre> and <code> tags from your html, so unfortunately these <div> wrapped code blocks would not be pretty, oh so pretty...
You could a) hack into the prettify plugin and force it to swallow div tags having certain classes or b) force tinyMCE to forget about these <p> wrappers.
For now, going with the second option, you can initialize tinyMCE with the following parameters:
forced_root_block : false,
force_br_newlines : true,
force_p_newlines : false
and with that you'll have your lines separated with <br> tags instead of wrapped in <p> tags. This is highly discouraged by the authors of tinyMCE for various reasons (refer to the FAQ), but it is still a valid option.
Now you can trick tinyMCE to wrap the whole content into a <code> block, with the following configuration (which is a bit of hack in itself, but works, ahemm mostly):
style_formats : [
{title : 'Codigo fuente', block : 'code', classes : 'prettyprint', wrapper: 1}
]
Your only problem that applying this style will strip the existing <br> tags from within your text selection. That's right, you'll have all your selected code compressed into one line. And I tried many ways to keep these tiny little miserable <br> tags, but could not pursuade tinyMCE to do so. This is where I gave up, hence the "half answer". Good luck!

Resources