Issue #2893Opened July 14, 2020by Hsin903210 reactions

[Question] Can I set for loop value in components render?

Question

Hi,I'm beginner in grapesjs. I want to make a question number by for loop when I dropped components, ↓I want final like this image. the div can show for loop number. 01

↓my component's code

 // default html
    const questionCom = 
   `<div class="gjs-row">
        <div class="gjs-cell">{{i}}</div>  //number variable
        <div class="gjs-cell"></div>
    </div>`;
    const dc = editor.DomComponents;
    const textType = dc.getType('text');
    editor.BlockManager.add('m2', {
            label: "question number",
            activate: true,
            content: {
                type:'m2',
                questionCom ,
         
            },  
        }),
        dc.addType('m2', {
            model: textType.model.extend({
                //...     
                }
            }),
            view:textType.view.extend({
                onActive(){
                    //...
                },
                render(val) {
                    var a=""
                    this.model.set('components', 
                          function a1(){  //on onActive I call function a1
                               for(var i=0;i<3;i++){ 
                                    a+=`<div class="gjs-row"><div class="gjs-cell">`+
                                           val+
                                           `</div><div class="gjs-cell"></div></div>`
                                }   
                                return a         
                            }
                       }
                      return this;
                },
            })
        });

In render, I divided the my default html questionCom from {{i}} into front and back. then,put them in render. {{i}} can perfect to show 1 2 3 in component.

but ,the divided method is not good. HTML can't easy to read and I can't set complex html if I want like↓

<div class="gjs-row"> //one div
        <div class="gjs-cell">  //two div
               <div class="gjs-row"> //three div
                        <div class="gjs-cell">{{i}}</div>  //four div
                        <div class="gjs-cell"></div>
                 </div> 
         </div> 
        <div class="gjs-cell"></div>
    </div>

Have any better method can solve my question? Thanks!

Answers (1)

artfJuly 29, 20200 reactions

Use the questionCom you're passing to the model (use model to update model related logic) and I'd suggest using API from the Components documentation (eg. textType.view.extend is the old one)

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.