how to set html inline css from django - html

Hi everyone,
I am stuck at one point while rendering the data from django views.
I want to use the CSS data produced in views to be used in the template.
I did all I could do,
i) inserted the element into the RequestContext, sent it to template
ii) From here, I tried to insert that CSS style data into div tag
This is my css data in VIEW( they are "left:xx px top: xx px" positions)
coords = {'usa':['usamap.png',['635px','322px'],['592px','381px'],['541px','398px'],['115px','582px']],
'canada':['canadamap.png',['201px','336px'],['377px','565px'],['420px','600px'],['441px','648px']]
}
template = loader.get_template('polls/phasex.html')
context = RequestContext(request,{'id_list':id_list,'country':country,'coords':coords[key],'temp':temp,})
return HttpResponse(template.render(context))
On template I am trying to access the data:
<div style={{'left: '|add:coords.1.0|add:'; top: '|add:coords.1.1|add:';'}} >
<text>{{'left: '|add:coords.1.0|add:'; top: '|add:coords.1.1|add:';'}}</text>
actually i should get this when i run:
<div style = 'left: 635px; top: 322px'>
But i am getting this on the webpage:
<div style="left:" 635px;="" top:="" 322px;="">
<text>left: 635px; top: 322px;</text>
</div>
I can't understand where's the problem? The text box was for debugging. It's printing properly, but i'm not getting the same inside css styles.
Thanks in Advance

You have to place variables inside quotes, like this:
<div style="left:{{ variable }}"></div>
And not like this
<div style={{ "left: variable" }}></div>

Related

Set content attribute of CSS as value between the brackets of HTML

In the scenario where the HTML look as follows:
<div>Text</div>
How can I get the value from between these tags ("Text", in this case) to be added as a value of CSS content attribute?
This how I would do it using React's term of that value:
div {
content: attr(children)
}
I don't know why you would need to do this but, you can in a way. I've included an example below but, it would help to know what your objective is.
var elem = document.getElementsByTagName("DIV");
elem[0].setAttribute('children',elem[0].textContent);
div:after {
content: attr(children)
}
<div>Text</div>
div:before{content:attr(data-text)}
<div data-text="text"></div>
i think you want to get that text using css so here is the way to get text via data attribute and css
<div>text</div>
TO
<div data-text="text">
If you want to place same text as data attr then put it
</div>
Now you can simpel put the css like
div:before {
content: attr(data-text)
}
Hope you this will helps you
Thanks

Pass a value from HTML to CSS

I was interested whether can I pass value to the css class from the html?
Like this
Example:
<div class="mt(5)"> Some text </div>
style {
.mt(#mpx) {
margin-top: #mpx px;
}
}
I've heard that such way was possible in Less
No, the way you want it is impossible in either CSS or any of its supersets (like Less and others). It's always HTML that uses values from CSS and not in opposite. Thus you'll need some scripting for what you need.
You can however pass values from HTML to CSS via Custom Properties using inline styles:
.c {color: var(--c)}
.m {margin: var(--m)}
<div class="c" style="--c: blue" >Foo</div>
<div class="m" style="--m: 0 2em">Bar</div>
<div class="c" style="--c: green">Baz</div>
Or even like this:
* {
color: var(--c);
margin: var(--m);
/* etc. */
}
<div style="--c: blue" >Foo</div>
<div style="--m: 0 2em">Bar</div>
<div style="--c: green">Baz</div>
But that method is no way different from styling by the plain vanilla method, i.e.:
<div style="color: blue">
... etc.
It is essentially same ugly and non-maintainable.
Many people try to achieve the goal by generating hundreds of predefined classes like .mt-1, .mt-2, ... .mt-99 etc. (since it's extremely easy thing to do in a CSS-preprocessor). But it's even more ugly solution (I won't bother you with details on why it is so. You'll read about that elsewhere or learn yourself after a few projects).
Maybe this is what you looking for? CSS: Attr()
You can bind the value to an attribute and then get this attribute back in the css, like this:
CSS
<p data-foo="hello">world</p>
CSS
[data-foo]::before {
content: attr(data-foo) " ";
}
Result
hello world
Here is a way of doing that without the use of LESS.
Use CSS variables:
Variables can be declared in the style attribute of the HTML elements.
Then, the CSS will catch the values from the HTML and apply the correct styles.
Add some JavaScript:
The values of the variables can now be dynamically modified.
⋅ ⋅ ⋅
Example of use:
Background color is set in the HTML, (fixed)
Padding of div1 will grow if clicked. (dynamic)
// When clicking on the div1, padding is gonna grow up.
document.getElementById("div1").onclick = function(){
var pad = this.style.getPropertyValue("--pad");
this.style.setProperty("--pad", parseInt(pad) + 1);
}
.divs {
background: var(--bg);
padding: calc(var(--pad)*5px);
}
<div id="div1" class="divs" style="--bg: #ff6; --pad: 1;">div1</div>
<div id="div2" class="divs" style="--bg: #f66; --pad: 2;">div2</div>
⋅ ⋅ ⋅
About CSS variables:
The variable names must begin with -- and are case sensitive.
These variables values are applied to the element and its children.
To use it globally, you can declare it on the body tag.
Here is a link with some examples: https://www.w3schools.com/css/css3_variables.asp

Show text inside div but treat it as a background image

I'm trying to create a div which has the initial text loading... inside of it, and can later be overlapped by new elements that are loaded into it. Here's what I'm dealing with:
<div class="results" style="position:relative;" *ngIf="showResults">
<!-- show 'loading...' before the results load, which would then overlap this text -->
<div stlye="position: absolute; z-index: -1;">Loading ...</div>
<!-- angular2 loop to asynchronously load results -->
<div *ngFor="let loc of searchLocations | async" (click)="selectLocation(loc)" class="search-result">
{{ loc.name }}, {{ loc.adminName1 }}, {{ loc.countryCode }}
</div>
</div>
But when I run this, here's what I get something like
so my 'loading...' text has it's own boundry, when i want those proceeding elements to overlap ontop of that text. How can I accomplish something like this?
You could create a boolean for the loader.
export class YourClass(){
isLoading:boolean = true;
constructor(){
// Not sure how you are implementing your GET Request
// So no point in trying to replicate that, just where ever
// you assign searchLocations to an object
// fetch data logic ends with => {
isLoading = false;
}
}
}
Then in your html you just need to add an *ngIf
<div style="position: absolute; z-index: -1;"
*ngIf="isLoading">Loading ...</div>
You could even even make the loader a component to use anywhere, or you could hook into the showResults variable, as long as you place the loading div outside the showResults div with an attribute of *ngIf="!showResults" , which might mean a bit of a style tweek.

How to parse attribute and value of a tag in html file at same time with Nokogori?

Say I have a html file called ex.html like following:
<ul>
<li data-value="datav1">val1</li>
<li data-value="datav2">val2</li>
<li data-value="datav3">val3</li>
</ul>
I want to extract attribute data-value and the text value line by line and output the result as below:
datav1:val1
datav2:val2
datav3:val3
However I'm new to Nokogori, all I know is the code below,which can only extract the attribute data-value, and I don't know how to extract attribute and text value in the same loop.
require 'nokogiri'
page_temp = Nokogiri::HTML(open("ex.html"))
page_temp.xpath('//li/#data-value').each do |node|
puts node
end
I'd really appreciate that if anyone can teach me how to make it work through Nokogori, and it would be better if there is any other solution could simply by using shell script.
UPDATE
Thanks for #Rajarshi Das and #Arun Kumar, your answers partly solved my problem. Now the problem is that node.text are some Chinese characters. And they are unrecognizable when I print them out in terminal.
I tried to print out the page_temp when after I executed page_temp = Nokogiri::HTML(open("ex.html")) and I find that all Chinese characters are like €. So I guess I read the ex.html file wrong in ruby.
You can try this way....
page_temp.xpath('//li').each do |node|
puts "#{node.attributes['data-value'].value}:#{node.children.first.content}"
end
and output get
datav1:val1
datav2:val2
datav3:val3
By nokogiri you can do it step by step like first step
page_temp.xpath('//li').each do |node|
you can get the output of what it give by just taking one item
page_temp.xpath('//li').first
#=> #<Nokogiri::XML::Element:0x1827ae0 name="li" attributes=[#<Nokogiri::XML::Attr:0x1827aa4 name="data-value" value="datav1">] children=[#<Nokogiri::XML::Text:0x182781c "val1">]>
now you need datav1:val1
so datav1 is in attributes
page_temp.xpath('//li').first.attributes
=> {"data-value"=>#<Nokogiri::XML::Attr:0x1827aa4 name="data-value" value="datav1">}
so to get it you can do page_temp.xpath('//li').first.attributes["data-value"].value
page_temp.xpath('//li').first.attributes["data-value"].value
#=>datav1
now for val1
there is also a children attribute of that nokogiri instance and it contains the element text/content
so
page_temp.xpath('//li').first.children
=> [#<Nokogiri::XML::Text:0x182781c "val1">]
page_temp.xpath('//li').first.children.first.content
=> val1
now get two desire output element in the loop use these as page_temp.xpath('//li').first replace by node and show it in desire format of string.
so it would be
"#{node.attributes['data-value'].value}:#{node.children.first.content}"
This should do it.
page_temp.xpath('//li').each do |node|
puts "#{node['data-value']}:#{node.text}"
end
The code is self-explanatory but let me explain. You're looping over all the li elements and printing the value of data-value attribute along with the text contained in the li element.
this work
<style>.Middle {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
width: 1350px;
background-color: blue;
border: 0px solid black;
}
</style>
<div align="center" class="Middle">
<select onChange="window.location.href=this.value">
<option>Change data</option>
<option value="http://www.mrdicky.cf/">data1</option>
<option value="http://www.mrdicky.cf/">data2</option>
<option value="http://www.mrdicky.cf/">data3</option>
</select>

Can i use attributes of element to create style rules?

I'm noot good in english, so the title may seem a bit odd.
I want to use css function attr() like this:
I mean i have a container <div> and an inner <div> that i want to have width depending on data-width attribute. For example this would be great, but this doesnt work:
<div class="container">
<div data-width="70%">
</div
</div>
.container {
width: 600px;
height: 200px;
}
.container div {
width: attr(data-width);
height: 100%;
}
Is there any noJS way to use attributes like that?
UPDATE: Guys convinced me that the JS is the only way to do this :)
That's not a big problem (but that's bad. CSS, why youre so illogical? Is the difference between content:attr(data-width) and width: attr(data-width) so big ?).
One of the guys had an idea to go through the all elements with jQuery.
That's ok, but it is very... local? Don't know how to say it in english.
Anyway, i remaked his code a little bit and here it is:
allowed = ['width','color','float'];
$(document).ready(function () {
$('div').each(function (i, el) {
var data = $(el).data(),style = '';
if (!$.isEmptyObject(data)) {
$.each(data, function (attr, value) {
if (allowed.indexOf(attr) != - 1) {
style += attr + ': ' + value + '; ';
}
})
if (style.length != 0) {
$(el).attr('style', style);
}
}
})
})
Idea is simple:
1. We suppose that style we want to add to an element is the only one. I mean there are no scripts that will try to add some other styles,
2. We create an array of allowed attribute names, we need to avoid using wrong names at the style attribute, for example style="answerid: 30671428;",
3. We go through each element, save its data attributes in an object, check if object is empty, and if not - check every attribute if it is allowed, create a string that contains all styles that we need, and - finally - add our style string to the element as the content of style attribute.
That's all, thanks everybody
I would not advise to use CSS alone since it will not allow you to do what you're looking for... instead use a scripting language (in my case jQuery) to accomplish this functionality for you like so: jsFiddle
jQuery
jQuery(document).ready(function(){
var dataElem; // to store each data attribute we come accross
jQuery('div').each(function(){ //loop through each div (can be changed to a class preferably)
dataElem = jQuery(this); //get the current div
if(dataElem.data('width')){ //make sure it exists before anything further
dataElem.width(dataElem.data('width')); //set the element's width to the data attribute's value
dataElem.css("background-color", "yellow");
}
});
});
HTML
<p>The links with a data-width attribute gets a yellow background:</p>
<div>
w3schools.com
</div>
<div class="me" data-width="50"> <!-- change value to see the difference -->
disney.com
</div>
<div>
wikipedia.org
</div>
Notes on the above:
each, data, width.
Instead of doing data-width, use a class attribute. An html tag can have mutliple classes separated by spaces, so if you wanted to be very precise, you could set up as many classes as you need. For instance:
<div class="w70 h100">
</div>
Then in your css:
.w70{
width: 70%;
}
.h100{
height: 100%;
}
And so on.
Is there any noJS way to use attributes like that?
No, you cannot use CSS to set the width of the element to it's data-width attribute. CSS does not allow for this as attr() is only currently available for the CSS content property which is only available on css pseudo elements (::before and ::after).
How can you achieve this with as little javascript as possible?
This is extremely easy to do using the native host provided DOM API.
Select the elements using Document.querySelectorAll().
Iterate the elements and apply the styles using Element.style which can be retrieved from the data-width attribute using Element.dataset
(Demo)
var items = document.querySelectorAll('#container div'), item, i;
for(i = 0; (item = items[i]); i++) item.style.width = item.dataset.width;