{{#eachthis.cards}} Maintain responsive Flex properties when iterating arrays using Handlebars-PHP Chinese Network Q&A
Maintain responsive Flex properties when iterating arrays using Handlebars
P粉098417223
P粉098417223 2023-09-02 23:45:35
0
1
500

I have the following code (using Handlebars, working code from JSFiddle):

{{#each this.cards}}

{{title}}

{{/each}}
{ "3columnLayout": false, "cards": [ { "title": "Card 1" }, { "title": "Card 2" }, { "title": "Card 3" } ] }

Basically, it loops through the array of cards and creates a card-container div for each item. Then use bootstrap to assign a CSS class to each div, for example col-md-6 so that:

  • Mobile: Items appear in a single column
  • Tablets: Items appear in 2 columns
  • Desktop: items displayed in 3 columns

This all works as expected and visually gives the desired UI (regardless of the number of cards): Example below:

However, as shown in the JSON, I need a property outside of the individual card level to determine whether the desktop should break from a 4-column layout to a 3-column layout.

I didn't want to repeat this property for every card in the card array, so reorganized my code as shown in my code snippet (using Handlebars): https://jsfiddle.net/stcfa5wh/20/< ;/p >

However, this now means that although I can access the 3columnLayout value: the HTML is dumped onto the page, and I can no longer use col in the way I do ;Done before.

For example, on a tablet, I could set each image-card to 50% width, but it ignores the need for rows.

Can anyone suggest a way to preserve the structure of the HTML while still implementing top-level attributes (e.g. 3columnLayout)?

P粉098417223
P粉098417223

reply all (1)
P粉309989673

I don't understand why you stopped using Bootstrap when you tried to implement the3columnLayoutflag. Using Bootstrap, we will create a 3 column layout using classcol-lg-4on each column. Therefore, the conditional expression we need for each column is:{{#if ../3columnLayout}}col-lg-4{{else}}col-lg-3{{/if}}.

const template = Handlebars.compile(document.getElementById('Template').innerHTML); const data = { "3columnLayout": true, "cards": [{ "title": "Card 1", }, { "title": "Card 2", }, { "title": "Card 3", }, { "title": "Card 4", }, { "title": "Card 5", }, { "title": "Card 6", }, { "title": "Card 7", }, { "title": "Card 8", } ] } const output = template(data); document.getElementById('Output').innerHTML = output;
.image-card { height: 432px; background-color: lightblue; border: 1px solid; margin-bottom: 16px; }
   
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!