Giving the example of svelte js tutorial about each blocks https://svelte.dev/tutorial/each-blocks how could I left align the first cat, right align the second one, left align the third one and so on if I had more elements.
Since you have the index available inside the each loop, you can set a class using the class:directive based on the condition if the index is dividable by 2 or not (in your case not, since you described to align the uneven indexes to the right) >> REPL
<script>
let cats = [
{ id: 'J---aiyznGQ', name: 'Keyboard Cat' },
{ id: 'z_AbfPXTKms', name: 'Maru' },
{ id: 'OUtn3pvWmpg', name: 'Henri The Existential Cat' }
];
</script>
<h1>The Famous Cats of YouTube</h1>
<ul>
{#each cats as { id, name }, i}
<li class:align-right="{i%2 !== 0}">
<a target="_blank" href="https://www.youtube.com/watch?v={id}">
{i + 1}: {name}
</a>
</li>
{/each}
</ul>
<style>
.align-right {
text-align: right;
}
</style>
Related
With the help of Lit library we have implemented the component that should render the list with items, where each item is rendered with a separate component:
<div>
<slot name="label"> Here goes the title </slot>
<slot name="list"></slot>
</div>
We pass data to the component like following:
<webc-list ?divided=${true}>
<span slot="label">Title</span>
<ul slot="list">
${items.map(
item =>
html`<webc-list-item
>${item}</webc-list-item
>`,
)}
</ul>
</webc-list>
My question is how can I pass the divided property to the <webc-list-item>.
I tried to access the elements
firstUpdated() {
const dividedProperty = this.divided;
this.renderRoot.querySelector('slot[name=list]')?.assignedElements({ flatten: true })
?.forEach(el => {
if (el && el.tagName && el.tagName.toLowerCase().includes('webc-list-item')) {
el.setAttribute('divided', `${dividedProperty}`);
}
});
But it doesn't work like this, any help would be appreciated!
I have a custom Gutenberg block (https://pastebin.com/bV2k5Ekc) in which I display text, link and an image. I want to change it so so instead of saving the image URL as a background image of the container, to use an img tag. Unfortunately - I can't manage to create the deprecation correctly - I fail at assigning the attributes parameters in the deprecation:
From this:
const {
attributes: {
mediaURL,
boxTitle,
boxDescription,
linkText,
linkHref,
linkTitle
},
className,
} = props;
let boxClass = 'cta-box';
let contentDescription = '';
if (boxDescription.length) {
boxClass += ' cta-box-description';
contentDescription = (
<p>
{boxDescription}
</p>
)
}
return (
<div className={`cta-block-box ${className}`}>
<a
className="cta-box-link"
href={linkHref}
style={{ backgroundImage: "url(" + mediaURL + ")" }}
rel="noopener noreferrer"
>
<div className={boxClass}>
<h3>
{boxTitle}
</h3>
{contentDescription}
<span className="arrow">{linkText ? linkText : linkTitle}</span>
</div>
</a>
</div>
);
},
To this (I only change what's in the return statement):
return (
<div className={`cta-block-box ${className}`}>
<a
className="cta-box-link"
rel="noopener noreferrer"
>
<img className="cta-box-image" src={linkHref} alt=""/>
<div className={boxClass}>
<h3>
{boxTitle}
</h3>
{contentDescription}
<span className="arrow">{linkText ? linkText : linkTitle}</span>
</div>
</a>
</div>
);
Which of course broke the Gutenberg element. So I added a deprecate to the blog, as much as I could following the official Wordpress documentation:
deprecated: [
{
attributes: {...this.attributes},
save: (props) => {
const {
attributes: {
mediaURL,
boxTitle,
boxDescription,
linkText,
linkHref,
linkTitle
},
className,
} = props;
console.log('dep');
console.log(props);
let boxClass = 'cta-box';
let contentDescription = '';
if (boxDescription.length) {
boxClass += ' cta-box-description';
contentDescription = (
<p>
{boxDescription}
</p>
)
}
return (
<div className={`cta-block-box ${className}`}>
<a
className="cta-box-link"
style={{ backgroundImage: "url(" + mediaURL + ")" }}
rel="noopener noreferrer"
>
<div className={boxClass}>
<h3>
{boxTitle}
</h3>
{contentDescription}
<span className="arrow">{linkText ? linkText : linkTitle}</span>
</div>
</a>
</div>
);
},
}
],
After this the editor page crashes, and I get error message in console, that attributes is not defined (displaying incorrect row in the script file). This is the "after" script contents (https://pastebin.com/dVdLMx7N).
react-dom.min.js?ver=16.13.1:125 ReferenceError: attributes is not defined
at save (cta-box2.js?f66a:242)
at Wt (blocks.min.js?ver=9ed25ffa009c799f99a4340915b6dc6a:3)
at Qt (blocks.min.js?ver=9ed25ffa009c799f99a4340915b6dc6a:3)
at block-editor.min.js?ver=4378547cec8f5157a02ead3dfc5c65b2:12
at hooks.min.js?ver=50e23bed88bcb9e6e14023e9961698c1:2
at $r (blocks.min.js?ver=9ed25ffa009c799f99a4340915b6dc6a:3)
at blocks.min.js?ver=9ed25ffa009c799f99a4340915b6dc6a:3
at Ur (blocks.min.js?ver=9ed25ffa009c799f99a4340915b6dc6a:3)
at blocks.min.js?ver=9ed25ffa009c799f99a4340915b6dc6a:3
at Array.reduce (<anonymous>)
Any help would be greatly appreciated! I suspect I'm missing some small detail, but so far I've failed to locate it. And was not able to find relevant enough information on the web.
Thanks in advance!
There are two issues in your "after" script:
The attributes do not match (and the this is actually the window object): attributes: {...this.attributes} (see line 212).
So what you used with the attributes property on line 24, should also be used with the same property on line 212. (because you only changed the output, so the block attributes remain the same)
The save output/markup also do not match — in the "before" script, you've got href={linkHref}, but in the deprecated property of the "after" script, the save output did not have that href. (see this diff)
So make sure the attributes and save output match the ones in the old/"before" script, and the following is how your code would look like, but note that I only included the main parts that need to be fixed:
// Define the attributes and use it with the root "attributes" property and
// the one in the "deprecated" property.
const blockAttributes = {
mediaID: {
type: 'number'
},
mediaURL: {
type: 'string'
},
boxTitle: {
type: 'string',
default: ''
},
// ... the rest of the attributes here.
};
registerBlockType('hswp/test-box', {
title: __('Test Box', 'modula'),
// ... your code.
attributes: blockAttributes,
// ... your code.
deprecated: [
{
attributes: blockAttributes,
save: (props) => {
// ... your code.
return (
<div className={`cta-block-box ${className}`}>
<a
className="cta-box-link"
href={linkHref}
style={{ backgroundImage: "url(" + mediaURL + ")" }}
rel="noopener noreferrer"
>
... your code.
</a>
</div>
);
},
}
],
});
Additionally, note that the PlainText component doesn't (as of writing) have a property named tagName.
I have array of items which are rendered on UI as angular material cards. I have a search box where user input for items. once the search is implemented I get the searchItems as another array. Now I want to highlight (changing the background color of the card or a rectangular animation) items array angular material cards which are matched with searched items. I was stuck at implementing this css part although I am able to render and match the items with searchdItems
<div *ngIf="searchedItems">
<div class="alert alert-danger alert-dismissible" *ngIf="searchedItems.length === 0">
×
<strong>{{data.value}}</strong> not found
</div>
<div *ngIf="searchedItems.length > 0" class='searchitem'>
{{data.value}} found in
<div *ngFor="let item of searchedItems; let i = index">
{{item}} {{i}}
</div>
</div>
</div>
<mat-grid-list cols="3" rowHeight="100px">
<div *ngFor="let item of items; let x = index">
<mat-grid-tile [ngClass]="item.name == item ? 'searchexample-card': 'example-card'" routerLink="/inventory/items/{{item.name}}">
<mat-card>
<mat-card-header>
<b>Item{{item.name}}</b>
</mat-card-header>
</mat-card>
</mat-grid-tile>
</div>
</mat-grid-list>
If you are unable to change the items array I have modified the answer for the pipe which will not impact your original array
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'highlight', pure: false
})
export class HighlightPipe implements PipeTransform {
transform(items: any, filtered?: any[]): any {
let newArray = [];
if(Array.isArray(items) && Array.isArray(filtered)) {
for(let item of items){
newArray.push({label: item, highlight: filtered.indexOf(item)>-1})
}
} else {
newArray = items.map(item => ({label: item}));
}
console.log(newArray)
return newArray;
}
}
But your html template will be modified to accommodate the highlight
<div *ngFor="let item of items | highlight: searchedItems" [ngClass]="{card: true, highlight: item.highlight}">
{{item.label}}
</div>
Here I am passing the array that you have after you search searchedItems to my highlight Pipe
Hope this answers your question
Updated Stackblitz: https://stackblitz.com/edit/angular-oyhva7
The problem is with the condition that you have implemented for activating [ngClass]. You are comparing an object with object property, this comparison for item with item.name will always return false.
consider you have the searched result in searchedItems[] array. Now you want to highlight those items in the loop of whole items. then your code should be something like this
<div *ngFor="let item of items; let x = index">
<mat-grid-tile [ngClass]="item in searchedItems ? 'searchexample-card': 'example-card'">
<mat-card>
<mat-card-header>
<b>Item{{item.name}}</b>
</mat-card-header>
</mat-card>
</mat-grid-tile>
</div>
Considering your items array and searchedItems[] is of same type.
You can do it using a pipe from Angular
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'highlight',
pure: false
})
export class HighlightPipe implements PipeTransform {
transform(items: any, search: string, clip: boolean): any {
const regex = new RegExp(search, 'ig');
if(Array.isArray(items) && search) {
for(let item of items) {
item.highlight = regex.test(item.label);
}
}
return clip ? items.filter(item => item.highlight) : items;
}
}
I have passed in the search term in the pipe and the full array always returning from the pipe, but using a regular expression or maybe your custom logic of search add another attribute to the list item highlight boolean which is true if your logic says it matches the item, else false
I have modified the items array from string[] to {label:string, highlight?:boolean}[] to accommodate the pipe change so instead we are using the array as
items: {label:string, highlight?:boolean}[] = [
{label: 'INDIA'},
{label: 'USA'},
{label: 'RUSSIA'},
{label: 'UK'},
{label: 'ITALY'},
];
Now to all put it into the template
<div
*ngFor="let item of items | highlight: search"
[ngClass]="{highlight: item.highlight, card: true}"
>
{{item.label}}
</div>
Here when you search, if it matches with any of the item from items array will have a highlight:true attribute as true and also adds a class called 'highlight` to your existing div.card so in css defining the highlight card as
.card.highlight{
background-color: yellow;
}
Notice that we are sending the search term to the pipe that we created as an argument, so we have to define the variable as a class level variable which is set when we click search in your method devicesearch which you are already calling.
search: string;
devicesearch(input) {
this.search = input;
}
Edit 2:
If you wanted the clipped array you can use the Pipe in your class to get the clipped array
search: string;
searchedItems: any[];
highlightPipe = new HighlightPipe();
devicesearch(input) {
this.search = input;
this.searchedItems = this.highlightPipe.transform(this.items, input, true);
// only names --> const names = this.searchedItems.map(item => item.label);
}
Updated StackBlitz for your reference: https://stackblitz.com/edit/angular-usswkn
This is my helper for generating a treeview.
Using this i am able to generate the treeview in the mvc5.
#helper GetTreeView(List<MvcTreeview.Models.Category> siteMenu, int parentID)
{
foreach (var i in siteMenu.Where(a => a.ParentID.Equals(parentID)))
{
<li>
#{var submenu = siteMenu.Where(a => a.ParentID.Equals(i.ID)).Count();}
#if (submenu > 0)
{
<span class="collapse collapsible"> </span>
}
else
{
<span style="width:15px; display:inline-block"> </span>
}
<span id="Category">
#i.CategoryName
#*oncontextmenu="return false"*#
</span>
#if (submenu > 0)
{
<ul>
#Treeview.GetTreeView(siteMenu, i.ID)
#* Recursive Call for Populate Sub items here*#
</ul>
}
</li>
}
}
This is my View for displaying
#model List<MvcTreeview.Models.Category>
#{
ViewBag.Title = "Simple";
}
<div class="gridbox gridleft">
<div class="left">
<div style="padding:10px; background-color:#FAFAFA">
<div class="treeview">
#if (Model != null && Model.Count() > 0)
{
<ul>
#Treeview.GetTreeView(Model, Model.FirstOrDefault().ParentID)
</ul>
}
</div>
</div>
</div>
</div>
<div id="onSuccess">
</div>
#* Here We need some Jquery code for make this treeview collapsible *#
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$(".treeview li>ul").css('display', 'none'); // Hide all 2-level ul
$(".collapsible").click(function (e) {
e.preventDefault();
$(this).toggleClass("collapse expand");
$(this).closest('li').children('ul').slideToggle();
});
});
function PassingFunction(clicked_id) {
url = '#Url.Action("Details", "TestDetails")';
$.ajax({
url: url,
type: 'GET',
data: { 'id': clicked_id },
success: function (returnData) {
$("#onSuccess").html(returnData);
console.log(returnData);
},
error: {
}
});
}
</script>
}
Now i want to add the custom functionalities to the nodes of the treeview
Add
Delete
Edit
How can i do that?
There is a lot of JQuery Context Menu options on this link.
I have just picked the most forked of them, jQuery contextMenu.
I created a JSFeed fork in an example of treeview using UL/LI and created this JSFiddle with the Context-Menu to help you:
http://jsfiddle.net/mqueirozcorreia/0h82qto6/
Explaining the code:
I have added the externals resources:
http://swisnl.github.io/jQuery-contextMenu/dist/jquery.contextMenu.min.css
https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js
http://swisnl.github.io/jQuery-contextMenu/dist/jquery.contextMenu.min.js
All the magic goes in the javascript code, configuring the context-menu.
The selector property will put the context menu in every element of type <span> and having class attribute with value "contextMenuItem":
selector: 'span.contextMenuItem',
When the user clicks the callback function below runs. In this example, it alerts/logs what key was selected and the id attribute value.
callback: function(key, options) {
var m = "clicked: " + key + " on element of id " + options.$trigger.attr("id");
window.console && console.log(m) || alert(m);
},
In Meteor, I have an app where I make a list of items grouped by tags, where non-tagged items come first and then tagged items are hidden under a "tag header" drop down.
I haven't touched this app since 0.8 came out, and I was using a block helper in a template which worked fine in pre-0.8...
See working jsfiddle here
Handlebars.registerHelper('eachItem', function(context, options) {
var ret = "";
for(var i=0, j=context.length; i<j; i++) {
if(!context[i].tag){
ret = ret + options.fn(context[i]);
} else {
if(i===0||!context[i-1].tag ||context[i-1].tag !== context[i].tag){
ret = ret + '<li class="list-group-item"><a data-toggle="collapse" data-target="#'+ context[i].tag +'"> Items tagged '+context[i].tag + '</a></li><div id="'+context[i].tag+'" class="collapse">';
}
ret = ret + options.fn(context[i]);
if(i+1<j && context[i+1].tag !== context[i].tag){
ret = ret + '</div>';
}
}
}
return ret;
});
But I'm struggling a bit to translate this into post-0.8 Meteor
The inserted HTML must consist of balanced HTML tags. You can't, for example,
insert " </div><div>" to close an existing div and open a new one.
One idea I had was to render the non-tagged items and also the containers in a vanilla {{#each}} loop (with 2 different templates), and then do something like this
Template.myListContainer.rendered = function(){
_.each(tags, function(tag){
var tagged_items = _.filter(items, function(item){ return item.tag == tag; });
_.each(tagged_items, function(item){
UI.insert(UI.RenderWithData(listItemTemplate, { item : item }), tagContainer);
});
});
}
Is there a simpler way to do this ? If the items come from a collection, will they keep their reactivity ?
Many thanks in advance !
If you haven't already, it's worth reading the Meteor wiki on migrating to blaze.
Anyhow, this one seems difficult to implement as a straight iteration.
If you don't need them in a specific order, I would just list items w/ and w/o tags, eg:
Template.example.helpers({
dataWithoutTags: function(){
return items.find({tag:{exists: false}});
},
tagList: function(){
// create a distinct list of tags
return _.uniq(items.find({tag:{exists: true}}, {tag: true}));
},
dataForTag: function(){
// use `valueOf` as `this` is a boxed-string
return items.find({tag: this.valueOf()});
}
});
Template:
<template name="example">
<div class='panel panel-default'>
<ul class='list-group'>
{{#each dataWithoutTags}}
<li class='list-group-item'>{{name}}</li>
{{/each}}
{{#each tagList}}
<li class="list-group-item">
<a data-toggle="collapse" data-target="#{{this}}"> Items tagged {{this}}</a>
</li>
<div id="{{this}}" class="collapse">
{{#each dataForTag}}
<li class='list-group-item'>{{name}}</li>
{{/each}}
</div>
{{/each}}
</ul>
</div>
</template>
If you do need them in a specific order - eg. grouping only consecutive items (as per your example). The only option would be to pre-process them.
eg:
Template.example.helpers({
itemsGrouped: function(){
dataGroups = [];
currentGroup = null;
items.find({}, {sort: {rank: 1}}).forEach(function(item){
if (currentGroup && (!item.tag || currentGroup.tag != item.tag)){
dataGroups.push(currentGroup);
currentGroup = null;
}
if (item.tag){
if (!currentGroup){
currentGroup = {
group: true,
tag: item.tag,
items: [item]
};
} else {
currentGroup.items.push(item);
}
} else {
dataGroups.push(item);
}
});
if (currentGroup){ dataGroups.push(currentGroup); }
return dataGroups;
}
});
Template:
<template name="example">
<div class='panel panel-default'>
<ul class='list-group'>
{{#each itemsGrouped}}
{{#if group}}
<li class="list-group-item">
<a data-toggle="collapse" data-target="#{{tag}}"> Items tagged {{tag}}</a>
</li>
<div id="{{tag}}" class="collapse">
{{#each items}}
<li class='list-group-item'>{{name}}</li>
{{/each}}
</div>
{{else}}
<li class='list-group-item'>{{name}}</li>
{{/if}}
{{/each}}
</ul>
</div>
</template>
If you log the value you are returning from the eachItem helper, you will see you are not closing the last div element. Fixing that may get it working again. However, you have div elements as direct children of the ul element, which you are not supposed to according to the HTML5 specification:
Permitted contents: Zero or more li elements
Also, I think it would be a better option for you to prepare your context in a format that makes it easier to let simple templates take care of the rendering. For example, using the same data from your jsfiddle, suppose you had it in the following format:
tagGroups = [{
names: ["item1", "item2"]
},{
tag: "red",
names: ["item3", "item4"]
},{
tag: "blue",
names: ["item5", "item6", "item7"]
}]
The following templates would give you the expected result in a valid html format. The ending result is a bootstrap panel containing collapsible list-groups:
<template name="accordion">
<div class="panel panel-default">
{{#each tagGroups}}
{{> tagGroup}}
{{/each}}
</div>
</template>
<template name="tagGroup">
{{#if tag}}
{{> namesListCollapse}}
{{else}}
{{> namesList}}
{{/if}}
</template>
<template name="namesList">
<ul class="list-group">
{{#each names}}
<li class="list-group-item">{{this}}</li>
{{/each}}
</ul>
</template>
<template name="namesListCollapse">
<div class="panel-heading"><a data-toggle="collapse" data-target="#{{tag}}">Items tagged {{tag}}</a></div>
<ul id="{{tag}}" class="panel-collapse collapse list-group">
{{#each names}}
<li class="list-group-item">
{{this}}
</li>
{{/each}}
</ul>
</template>
And here is an example of a helper to transform your data so you can make a quick test to see it working:
Template.accordion.tagGroups = function () {
var data = [{
name : 'item1'
},{
name : 'item2'
},{
name : 'item3',
tag : 'red'
},{
name : 'item4',
tag : 'red'
},{
name : 'item5',
tag : 'blue'
},{
name : 'item6',
tag : 'blue'
},{
name : 'item7',
tag : 'blue'
}];
data = _.groupBy(data, 'tag');
data = _.map(data, function (value, key) {
var obj = {};
if (key !== 'undefined') {
obj.tag = key;
}
var names = _.map(value, function (item) {
return item.name;
});
obj.names = names;
return obj;
});
//console.dir(data);
return data;
};
And yes, if the items come from a collection, you will get reactivity by default.