Nested elements naming style (Jade, HAML, Slim) - css

Looking for solution how to use SMACSS naming convention with jade, haml or slim template engine.
Expect following jade code :
.module
.child
.child
as output i'll get following:
<div class="module">
<div class="child"></div>
<div class="child"></div>
</div>
but i'd like to reach following result:
<div class="module">
<div class="module-child"></div>
<div class="module-child"></div>
</div>
is there any solution to manage it like i can do it in SASS for example, i mean avoid adding 'module-' string to each 'child' manually ?
UPDATE
Also acceptable solutions with Haml and Slim

This is the closest I got with jade (live playground here):
mixin e(elt)
- var a = attributes;
- var cl = attributes.class;delete attributes.class
- var elt = elt ? elt : 'div' // If no parameter given
if cl
- var cl = parent + '-' + cl
else
- var cl = parent
#{elt}&attributes({'class': cl}, attributes)
block
- var parent = 'box'
+e('aside')#so-special
+e('h2').title Related
+e('ul').list
+e('li').item: +e('a')(href='#').link Item 1
+e('li').item: +e('span').link.current Item 2 and current
+e('li').item#third(data-dash='fine', aria-live='polite') Item 3 not even a link
| multi-line
| block
// - var parent = 'other' problem of scope I guess
+e('li').item lorem ipsum dolor sit amet
- var parent = 'footer'
+e('footer')(role='contentInfo')
+e.inner © Company - 2014
A mixin named e will output an element taken as a parameter (default is div) with its attributes and content as is, except for the first class that'll be prefixed with the value of the variable parent (or will be the value of parent itself if it hasn't any class)
I prefer using default jade syntax for attributes, including class and id than passing many parameters to a mixin (this one doesn't need any if it's a div, as with .sth text'd output <div class="sth>text</div> and +e.sth text will output <div class="parent-sth>text</div>)
Mixin would be shorter if it didn't have to deal with other attributes (href, id, data-*, role, etc)
Remaining problem: changing the value of parent has no effect when it's indented. It had with simpler previous attempts so I guess it's related to scope of variables. You theoretically don't want to change the prefix for child elements but in practice... Maybe as a second optional parameter?
Things I had problem with while playing with jade:
attributes doesn't work as expected. Now it's &attributes(attributes). Thanks to jade-book issue on GitHub
but it'll output class untouched plus the prefixed one, so I had to remove it (delete) in a place it'd be executed by jade

Some thoughts from me: what's wrong with a variable?
- var myModule = 'module'
div(class="#{myModule}")
div(class="#{myModule}-child")
div(class="#{myModule}-child")
or combine it with an each:
- var myModule2 = 'foobar'
div(class="#{myModule2}")
each idx in [0, 1, 2, 3]
div(class="#{myModule2}-child") I'm child #{idx}
Sure, there is much more code to write, but if a change is neccessary then you must do this only at one point.
Ciao
Ralf

You should be able to achieve this with SASS. As long as you have the latest SASS version, you should be able to use the following syntax:
.module {
&-child {
}
}
Have a look at this article for more information on newer features of SASS http://davidwalsh.name/future-sass

Related

Is there a better way to do this in handlebars?

Im using handlebars to spit out some static pages using a partial like so:
{{> component/card size="small" title="Card Title" }}
Now depending on the "size" of the card required, i need to set some different tailwind classes. Im currently doing it like so, but there must be a better way? Adding the class to the container and writing css is not an option.
{{setVariable "additionalHeadingClass" "text-5 md:text-6 mb-4"}}
{{#ifEquals size "small"}}
{{setVariable "additionalHeadingClass" "text-4 mb-1"}}
{{/ifEquals}}
{{#ifEquals size "large"}}
{{setVariable "additionalHeadingClass" "text-4 sm:text-5 md:text-8 mb-4"}}
{{/ifEquals}}
<h3 class="text-primary font-bold {{#root.additionalHeadingClass}}">{{title}}</h3>
and heres the helper im using:
Handlebars.registerHelper("setVariable", function (varName, varValue, options) {
if (!options.data.root) {
options.data.root = {};
}
options.data.root[varName] = varValue;
});
My opinion is that there is too much code in your template for what it actually does. Despite the intimidating number of lines, we really just want to map a size to a string of class names. I would also advise against the setVariable because I find it harder to think about when we creating a side-effect by manipulating a variable on our context object. I would much prefer a more functional-style helper, where we just give it the size and it returns the class names string.
I would create such a helper using a simple switch:
Handlebars.registerHelper('additionalClasses', function(size) {
switch (size) {
case 'large':
return 'text-4 sm:text-5 md:text-8 mb-4';
case 'small':
return 'text-4 mb-1';
default:
return 'text-5 md:text-6 mb-4';
}
});
And then we may reduce our template to the much simpler:
<h3 class="text-primary font-bold {{additionalClasses size}}">{{title}}</h3>
I have created a fiddle for reference.

What CSS should I write in html template to generate a pdf of a particular height & width

I am generating a PDF using nodejs with pdf-creator-node and I got success.
My requirement is I need to generate a PDF with Height X Width = 926px X 1296px.
I don' know what css I should write to generate this dimension pdf.
right now if I set div or body height and widht with above mentioned dimension I am getting 3 pages
this is what I tried
#page {
width: 1296px;
height: 926px;
}
<div
class="parent-div"
style="
width: 1296px;
height: 926px;
background-color: #faf0e6;
border: 1px solid red;
"
></div>
jsPDF is able to use plugins. In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:
Go to https://github.com/MrRio/jsPDF and download the latest
Version.
Include the following Scripts in your project:
jspdf.js
jspdf.plugin.from_html.js
jspdf.plugin.split_text_to_size.js
jspdf.plugin.standard_fonts_metrics.js
If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this:
<!DOCTYPE html>
<html>
<body>
<p id="ignorePDF">don't print this to pdf</p>
<div>
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>
Then you use the following JavaScript code to open the created PDF in a PopUp:
var doc = new jsPDF();
var elementHandler = {
#ignorePDF': function (element, renderer) {
return true;
}
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
source,
15,
15,
{
'width': 180,'elementHandlers': elementHandler
});
doc.output("dataurlnewwindow");
**For me this created a nice and tidy PDF that only included the line 'print this to pdf'.
Please note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue. It states:**
Because the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported.
Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like:
var elementHandler = {
#ignoreElement': function (element, renderer) {
return true;
},
#anotherIdToBeIgnored': function (element, renderer) {
return true;
}
};
From the examples it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit too unrestrictive for the most use cases though:
We support special element handlers. Register them with a jQuery-style ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) There is no support for any other type of selectors (class, of the compound) at this time.
One very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3, etc., which was enough for my purposes. Additionally, it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example:
<body>
<ul>
<!-- This is printed as the element contains a textnode -->
<li>Print me!</li>
</ul>
<div>
<!-- This is not printed because jsPDF doesn't deal with the value attribute -->
<input type="textarea" value="Please print me, too!">
</div>
</body>

Angular 6: Update NG Style with function

I'm here today because I'm wondering something about the NG Style with Angular (my version being the 6). How can i update [ngStyle] when I use a function to return a value.
As always, here is a simplified example of my problem:
I generate div from an array of objects.
For each section, there are two div: one on the left and one on the right.
The size of the left div changes depending on the content, so it can do both 50px and 125px.
I want the right div to fit the size of the one on his left, always half that size (2 in getLeftDivHeight).
Obviously, this will be done in each section (Container).
How can I make the ngStyle update when the div's height to the left changes (due to resizing, adding content, or page display time)? )
Here is the code:
HTML
<section class = "Container" *ngFor="let oneContent of allContent">
<div id = "{{oneContent.id}}" style="float: left">
<p> {{oneContent.Content}} </ p>
</div>
<div style="float: right" [ngStyle]="height: getLeftDivHeight(oneContent.id, 2)">
</div>
</div>
Typescript (only the related function)
getLeftDivHeight(id: string, divisionNumber: number): string {
height = document.GetElementById(id).getBoundingClientRect().height /
divisionNumber;
return height + 'px';
}
Note that I am not looking for an HTML solution, but an Angular one, the code above is just an example to explain my problem.
Thank you in advance
You could return the whole style string, for example height: 100px, from the getLeftDivHeight method
getLeftDivHeight(id: string, divisionNumber: number): string {
height = document.GetElementById(id).getBoundingClientRect().height / divisionNumber;
return `height: ${height}px`;
}
or you could use the below syntax in the template
[style.height.px]="getLeftDivHeight(parameters)"
return only numerical height value from the method.
So, I finally manage to do it, using a directive.
I used ElementRef to access the HTML Object of my right div.
import {ElementRef,Renderer} from '#angular/core';
constructor(private el: ElementRef,public renderer: Renderer) {}
Then, I used Dom to access the left div height
this.el.nativeElement.parentElement.childElement[0].clientHeight;
Then I use this.renderer.setElementStyle() to apply style
I also learn that use offscrollheight to do the math is not a good idea !

Change CSS class's property on click

I've read around a little bit and have a good start to what I ultimately want. This was helpful, along with another article which I forgot the link to. However, everything I've read ADDS a CSS class or property to an element. I want to CHANGE a property of an existing CSS class, but I don't know how to target it.
I think I want to use ng-class in one of these use cases taken from the Angular documentation:
If the expression evaluates to a string, the string should be one or more space-delimited class names.
If the expression evaluates to an object, then for each key-value pair of the object with a truthy value the corresponding key is used as a class name.
My existing code uses ng-class along with some controller logic.
HTML
<div ng-controller="ngToggle">
<div ng-class="{'inset-gray-border' : style}">
<div class="subcontainer" ng-click="toggleStyle()">{{item.name}}</div>
</div>
</div>
This currently adds the inset-gray-border class to the nested div, but I just want to change the border property in the subcontainer class.
Controller
angular.module('app').controller('ngToggle', ['$scope', function($scope) {
$scope.style = false;
$scope.toggleStyle = function() {
$scope.style = $scope.style === false ? true: false;
};
}]);
I considered using a directive, but I believe that would be overkill. I think this can be achieved in a controller.
EDIT: After further research I think jQLite can do the trick, but that would probably require a directive.
CHANGE a property of an existing CSS class
Add a css rule that does that using the new class you added using ng-class. The specificity will over ride the original rule
.subcontainer{
color : blue
}
.inset-gray-border .subcontainer{
color:red
}
Instead of a big toggleStyle function, you can write that stuff in UI side only.
Here is fiddle. As you want to change border property of .subcontainer, Overwrite that property by adding .insert-gray-border
<div ng-controller="ngToggle">
<div >
<div ng-class="{'subcontainer':true,'inset-gray-border' : style}" ng-click="style=!style">{{item.name}}</div>
</div>
</div>
The benifit of this is , it uses local scope instead of controller scope.
The best bet would be to have two CSS classes defined, one for the base (untoggled) case, another with all the properties that you want for when the property is toggled on.
In this case you may want something like:
.container .subcontainer {}
.container .subcontainer-bordered { border: solid 1px #123456}
Then your HTML code be updated to reflect this structure
<div ng-controller="ngToggle">
<div class="container">
<div class="subcontainer" ng-class="{'subcontainer-bordered': style}" ng-click="style = !style">{{item.name}}</div>
</div>
</div>

How to apply CSS to second word in a string?

If I have the following string: John Smith, how could I use CSS to set font-weight: bold on the second word in order to achieve: John Smith.
Can this be done in pure CSS?
Update: I am retrieving user's name from the server, so in my template it is #{user.profile.name}.
Since a js solution was suggested and pure CSS isn't presently possible: Live demo (click).
Sample markup:
<p class="bold-second-word">John Smith</p>
<p class="bold-second-word">This guy and stuff.</p>
JavaScript:
var toBold = document.getElementsByClassName('bold-second-word');
for (var i=0; i<toBold.length; ++i) {
boldSecondWord(toBold[i]);
}
function boldSecondWord(elem) {
elem.innerHTML = elem.textContent.replace(/\w+ (\w+)/, function(s, c) {
return s.replace(c, '<b>'+c+'</b>');
});
}
It cannot be done in pure CSS, sorry. But if you are willing to accept a JavaScript fix, then you might want to look into something like this:
Find the start and end index of the second word in the element's textContent.
Add contenteditable attribute to element.
Use the Selection API to select that range.
Use execCommand with the bold command.
Remove contenteditable attribute.
EDIT: (just saw your edit) I agree this is a bit too hack-y for most uses. Perhaps you'd be better off saving what the last name is as meta-data?
It seems to be impossible by using only pure CSS. However, with a bit of JS you could get there pretty easily:
const phrases = document.querySelectorAll('.bold-second-word');
for (const phrase of phrases) {
const words = phrase.innerHTML.split(' ');
words[1] = `<b>${words[1]}</b>`; // this would return the second word
phrase.innerHTML = words.join(' ');
}
<p class="bold-second-word">John Smith</p>
<p class="bold-second-word">Aaron Kelly Jones</p>

Resources