【问题标题】:Dynamically add blocks to GrapesJS向 GrapesJS 动态添加块
【发布时间】:2020-06-07 19:58:19
【问题描述】:

我正在从数据库中检索动态 HTML、CSS 和 JS 代码。我怎样才能用这个创建块? 目前,这是我的代码,

editor.BlockManager.add(aBlock['name'], {
    id: aBlock['name'],
    label: aBlock['name'],
    category: aBlock['category'],
    content: aBlock['html'],
    style: aBlock['css'],
    script: aBlock['css'],
  });

但它不起作用。请帮忙。

【问题讨论】:

    标签: javascript grapesjs


    【解决方案1】:

    添加块元素后尝试console.log()。

    console.log('All block element ', blockManager.getAll());
    

    如果您的新块元素存在块对象数组,则只需再次渲染块元素。

    editor.BlockManager.render()
    or maybe like this
    editor.BlockManager.render(blockManager.getAll())
    

    https://grapesjs.com/docs/api/block_manager.html#render

    【讨论】:

      【解决方案2】:

      您可以在名为“components”的数组中推送组件,在我的示例中有两个组件。

      注意 1:我使用 angularjs 作为示例:

      var components = [
            {
              'id' : '0001',
              'data' : {
                   label: `<div>
                    <div class="my-label-block">Párrafo</div>
                  </div>`,              
                  content: {
                  type: "text",
                  content: '<span style="margin:0; font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 24px;">Ejemplo.</span>'
                },
                attributes: {
                class: "fa 0001",
                id: '0001'
                },
                category: 'Basic element'
              }
            }
      ,
          {
            'id' : '0002',
            'data' : {
                   label: `<div>
                    <div class="my-label-block">Botón</div>
                  </div>`,                  
                  content:`
                          <a style="font-family: Arial;">Button </a>
                  `,
                  editable: true,
                  draggable: true,
                  stylable: true,
                  category: 'Basic element',
                  selectable: true,
                  class : 'fa 0002',
                  attributes: {
                  class: "fa 0002",
                  id: '0002'
                  }
      
            }
          }
      ]
      

      然后,动态插入你的grapesJS实例:

      let bm = $scope.editor.BlockManager;
                for (i=0;i<components.length;i++){
                  if(components[i].id && components[i].data){
                    bm.add(components[i].id, components[i].data)
                  }
                }
      

      【讨论】:

        猜你喜欢
        • 2022-10-31
        • 1970-01-01
        • 2023-03-22
        • 2020-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        相关资源
        最近更新 更多