Issue #1942💬 RespondidoAbierto el 3 de abril de 2019por demodesignReacciones 0

No se pudieron cargar comentarios condicionales HTML mientras editamos la plantilla

Respuesta rápidapor demodesign

Por favor, ayudadme

Lee la respuesta completa abajo ↓

Pregunta

Al editar la plantilla, el comentario condicional se elimina con el renderizado automático pero funciona cuando intentamos importar y guardar

función email_editor(id) {
 ShowProg();
 $.getJSON(hostname + 'source/data.php', función (gjs_images) {
  HideProg();
  localStorage.clear();
  var CID = 'GJS';
  var content = $('#' + id).val();
  si (tipode tinymce != 'indefinido') {
   si (tinymce.get(id) != null) {
    content = tinymce.get(id).getContent();
   }
  }

var wrapperStyle = '';
  si (contenido) {
   var c = $(contenido),
           wrapperId = c.attr('id');
   if (wrapperId == 'wrapper') {
    wrapperStyle = c.attr('style');
    contenido = c[0].innerHTML;
   }
  }
  
var ws = wrapperStyle.split(';');

$('body').addClass('gjs-overflow').append('<div id="' + cid + '" style="height: 0px; overflow: hidden;">' +
          Contenido +
          '\<style>n' +
          '#wrapper { ' + wrapperStyle + ' }\n ' +
          '.container {\n ancho: 600px; margin: 0 auto;\n }\n ' +
          '.button {\n font-size: 20px;\n relleno: 10px 25px;\n color de fondo: #673AB7;\n color: #fff;\n text-align: center;\n borde-radius: 4px;\n tipo-peso: 300; \n pantalla: inline-block; margen: 10px;\n }\n ' +
          '.list-item {\n altura: auto;\n ancho: 100%;\n margen: 0 auto 10px auto;\n relleno: 5px;\n }\n ' +
          '.lista-celda-elementos{\n color-fondo: rgb(255, 255, 255);\n radio-borde: 3px;\n desbordamiento: oculto;\n relleno: 0;\n }\n ' +
          '.lista-celda-izquierda {\n ancho: 30%;\n relleno: 0;\n pantalla: bloque en línea;\n }\n ' +
          '.lista-celda-derecha {\n ancho: 70%;\n color: rgb(111, 119, 125);\n tamaño-fuente: 13px;\n altura-línea: 20px;\n relleno: 10px 20px 0px 20px;\n pantalla: bloque en línea;\n vertical-alineado: arriba;\n }\n ' +
          '.list-elemento-contenido {\n borde-colapso: collapse;\n margen: 0 auto;\n relleno: 5px;\n ancho: 100%;\n }\n ' +
          '.list-item-image {\n color: rgb(217, 131, 166);\n font-size: 45px;\n width: 100%;\n }\n ' +
          '.grid-element-image-image {\n line-height: 150px;\n font-size: 50px;\n color: rgb(120, 197, 214);\n margen-bottom: 15px;\n width: 100%;\n }' +
          '.grid-elemento-row {\n margin: 0 auto 10px;\n relleno: 5px 0;\n ancho: 100%;\n }\n ' +
          '.carta-elemento-cuadrícula {\n ancho: 100%;\n relleno: 5px 0;\n margen-inferior: 10px;\n }\n ' +
          '.grid-item-card-cell {\n color-fondo:rgb(255, 255, 255);\n desbordamiento: oculto;\n radio-borde: 3px;\n text-align: center;\n relleno: 0;\n }\n ' +
          '.grid-elemento-card-content {\n font-size: 13px;\n color: rgb(111, 119, 125);\n relleno: 0 10px 20px 10px;\n ancho: 100%;\n altura-línea: 20px;\n }\n ' +
          '.grid-elemento-celda2-l {\n vertical-align: top;\n relleno-derecha: 10px;\n ancho: 50%;\n pantalla: inline-block;\n }\n ' +
          '.grid-elemento-celda2-r {\n vertical-align: top;\n acolchado-izquierda: 10px;\n ancho: 50%;\n pantalla: inline-block;\n }\n ' +
          'img {\n ancho: 100%;\n }\n ' +
          '.control-forma{display: block; width: 100%; addding: .5rem .75rem; font-size: 1rem; line-height: 1.25; color: #55595c; background-color: #fff; background-image: none; -webkit-back-clip: addding-box; background-clip: addding-box; border: 1px solid rgba(0,0,0,15); border-radius: .25rem;}\n ' +
          '.grupo-forma { posición: relativo; margen-fondo: 1rem; }\n ' +
          '.input-group { posición: relativa; ancho: 100%; display: table; border-collapse: separate; }\n ' +
          '.input-group-addon { display: table-cell; addding: .5rem .75rem; margin-bottom: 0; font-size: 1rem; font-weight: 400; line-height: 1.25; color: #55595c; text-align: center; background-color: #eceeef; border: 1px solid rgba(0,0,0,.15); border-radius: .25rem; }\n ' +
          '.btn { display: inline-block; font-weight: 400; line-width: 1.25; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; user-select: none; border: 1px solid transparent; addding: .5rem 1rem; font-size: 1rem; border-radius: .25rem; } \n' +
          '.btn-primary { background-color: #3662b1; color:#fff; } \n' +
          '</style>' +
          '</div>');
  Configura el editor GrapesJS con el plugin de boletín
  
editor = grapesjs.init({
   autorender: Cierto,
   clearOnRender: cierto,
   Altura: '100%',
   storageManager: {
    id: 'gjs-nl-',
   },
   assetManager: {
    Activos: gjs_images,
    Upload: nombre de host + 'source/upload.php'
   },
   contenedor: '#' + cid,
   fromElement: cierto,
   Plugins: ['GJS-Preset-Newsletter', 'GJS-plugin-CKEDITOR', 'html-block', 'GJS-blocks-BASIC'], //, 'GJS-Aviary'
   pluginsOpts: {
    'gjs-preset-newsletter': {
     modalLabelImport: 'Pega todo tu código aquí abajo y haz clic en importar',
     modalLabelExport: 'Copia el código y úsalo donde quieras',
     codeViewerTheme: 'material',
     importPlaceholder: '',
    }, 'gjs-plugin-ckeditor': {
     Posición: 'Centro',
     Opciones: {
      startupFocus: cierto,
      extraAllowedContent: '*(*);*{*}', // Permite cualquier clase y cualquier estilo en línea
      allowedContent: true, // Desactivar el formato automático, eliminación de clases, etc.
      enterMode: CKEDITOR. ENTER_BR,
      Plugins extra: 'sharedspace,justificify,colorbutton,colordialog,panelbutton,font,shortcodes,emojione',
      Barra de herramientas: [
       {nombre: 'estilos', objetos: ['Fuente', 'TamañoFuente', 'ProspectShortcodes', 'EstáticoShortcodes', 'PersonalizadoShortcodes', 'Emojione']},
       ['Negrita', 'Cursiva', 'Subrayado', 'Golpe'],
       {nombre: 'párrafo', grupos: ['alineación'], elementos: ['JustificaIzquierda', 'JustificaCentro', 'JustificaDerecha', 'BloqueoJustificación']},
       {nombre: 'enlaces', objetos: ['Enlace', 'Desvincular']},
       {nombre: 'colores', objetos: ['ColorTexto', 'BGColor']}
      ],
     }
    }/*, 'gjs-aviary': {
     clave: '1',
     onApply: función (url, nombre de archivo, imageModel) {
     console.log(url, nombre de archivo, imageModel);
     editor. AssetManager.add({ src: newUrl, nombre: nombre de archivo });
     imageModel.set('src', newURL); Actualizar el componente de imagen
     }
     }*/
   }
  });

si (ws) {
   var WC = Editor. DomComponents.getWrapper();
   var wstyles = {};
   para (var i = 0; i < ws.length; i++) {
    var st = ws[i].split(': ');
    st[0] = st[0].trim();
    si (st[0] != 'indefinido' && st[0] != '') {
     wstyles[st[0]] = st[1];
    }
   }
   wc.set({
    Estilo: Wstyles
   });
  }

bm = editor. Jefe de bloque;
  si (plantillas != indefinido) {
   $.each(plantillas, función (k, v) {
    create_template_block(v);
   });
  }

Interruptor de categorías
  Categorías VAR = editor. BlockManager.getCategories();
  categories.each(category => {
   category.set('open', false).on('change:open', opened => {
    opened.get('open') && categories.each(category => {
     categoría !== abierto && categoría.set('abierto', falso);
    })
   })
  });

Vamos a añadir a esta demo la posibilidad de probar nuestros boletines
  var pnm = editor. Paneles;
  pnm.addButton('options', [{
    id: 'previa',
    Contexto: F,
    claseNombre: 'fa fa-eye',
    atributos: {
     título: 'Avance',
     'data-tooltip-pos': 'abajo'
    },
    comando: función () {
     return editor.runCommand('previsualización')
    }
   }, {
    id: 'deshacer',
    claseNombre: 'fa fa-undo',
    atributos: {
     título: 'Deshacer',
     'data-tooltip-pos': 'abajo'
    },
    comando: función () {
     editor.runCommand('core:undo')
    }
   }, {
    id: 'rehacer',
    claseNombre: 'fa fa-repeat',
    atributos: {
     título: 'Rehacer',
     'data-tooltip-pos': 'abajo'
    },
    comando: función () {
     editor.runCommand('core:redo')
    }
   }, {
    id: 'Claro',
    claseNombre: 'fa fa-basura icono-blank',
    atributos: {
     título: 'Tela transparente',
     'data-tooltip-pos': 'abajo'
    },
    Orden: {
     run: function (editor, sender) {
      sender & & sender.set('active', false);
      if (confirm('¿Estás seguro de limpiar el lienzo?')) {
       editor. DomComponents.clear();
       setTimeout(función () {
        localStorage.clear()
       }, 0)
      }
     }
    }
   }, {
    id: 'save_template',
    claseNombre: 'fa fa-save',
    atributos: {
     título: 'Guardar plantilla',
     'data-tooltip-pos': 'abajo',
    },
    Orden: {
     run: function () {
      var ihtml = editor.runCommand('gjs-get-inlined-html');
      if (!ihtml) {
       return false;
      }
      ihtml = ihtml.replace(' id="wrapper"', '');
      ihtml = ihtml.replace('<html><body>', '');
      ihtml = ihtml.replace(''</body></html>, '');

senddata('composer/template_create', {html: ihtml}, 'modal-body', '', JSON.stringify({title: 'Save Plantilla', modal: 'modal'}), function () {
       Toggle
       var a = $('.modal-body #addcategory'),
               c = $('.modal-cuerpo #category'),
               n = $('.cuerpo-modal #new_category');
       a.hide();
       c.change(función () {
        var que = $(esto),
                campaña = that.val();
        if (campaña == 'nuevo') {
         a.show();
         n.attr('disabled', false);
        } else {
         a.hide();
         n.attr ('discapacitado', cierto);
        }
       });
      });
     }
    }
   }, {
    id: 'someter',
    claseNombre: 'fa fa-check icon-check',
    atributos: {
     título: 'Salvar y cerrar',
     'data-tooltip-pos': 'abajo',
    },
    Orden: {
     run: function (editor, sender) {
      var inlined_html = editor.runCommand('gjs-get-inlined-html');
      si (tipode tinymce != 'indefinido') {
       si (tinymce.get(id) != null) {
        tinyMCE.get(id).setContent(inlined_html);
       } else {
        $('#' + id).val(inlined_html);
        UpdateIframe(id);
        $('#' + id + '-preview').html(inlined_html);
       }
      } else {
       $('#' + id).val(inlined_html);
       UpdateIframe(id);
       $('#' + id + '-preview').html(inlined_html);
      }

editor. DomComponents.clear();
      setTimeout(función () {
       localStorage.clear()
      }, 0);
      $('#' + cid).remove();
      $('body').removeClass('gjs-overflow');
     }
    }
   }, {
    id: 'cerca',
    NombreClase: 'fa fa-cerrar icono-cerrar',
    atributos: {
     título: 'Cerca',
     'data-tooltip-pos': 'abajo',
    },
    Orden: {
     run: function (editor, sender) {
      if (confirmar('¿Estás seguro de que quieres cerrar esto?')) {
       editor. DomComponents.clear();
       setTimeout(función () {
        localStorage.clear();
       }, 0);
       $('#' + cid).remove();
       $('body').removeClass('gjs-overflow');
      }
     }
    }
   }]);
   
var textnodeType = editor. DomComponents.getType('textnode');
   
editor. DomComponents.addType('comment', {
	  model: textnodeType.model.extend({
        toHTML() {
          return '<!--${this.get('content')}-->';
        },
      },{
        isComponent(el) {
          if (el.nodeType == 8) {
            return {
              etiquetaNombre: 'NULL', // solo necesito esto para evitar alguna regla de analizador
              Tipo: 'comentario',
              contenido: el.textContent
            }
          }
        },
      }),
	  view: textnodeType.view.extend({
		  render: función () {
			  this.el.style.display = "ninguno";
			  devuelvo esto;
		}
	}),
  });
  
Embelecer las descripciones emergentes
  var titles = document.querySelectorAll('*[título]');
  para (var i = 0; i < titles.length; i++) {
   var el = títulos[i];
   var title = el.getAttribute('título');
   título = título ? title.trim() : '';
   if (!título)
    pausa;
   el.setAttribute('data-tooltip', título);
   el.setAttribute('título', '');
  }
 });
}

Respuestas (3)

demodesign6 de abril de 2019

Por favor, ayudadme

artf10 de abril de 2019

Por favor, utiliza la función de búsqueda en los problemas.

Si hubieras intentado buscar 'HTML condicional comments', habrías encontrado la solución...

lock[bot]15 de abril de 2020

Este hilo se ha bloqueado automáticamente porque no ha habido actividad reciente desde que se cerró. Por favor, abre un nuevo problema para bugs relacionados.

Preguntas y respuestas relacionadas

Continúa investigando con debates sobre temas similares.

Plugins de pago que cumplen con este problema

Seleccionado por temas clave y relevancia de etiquetas para ayudarte a enviar más rápido.

Ver todos los plugins

Cargando recomendaciones de plugins de pago...

Opción gratuita

Consulta los plugins de código abierto de GrapesJS en GitHub O haz una búsqueda rápida en nuestro catálogo gratuito.

Explora plugins gratuitos →
Opción premium

Los plugins premium incluyen soporte, actualizaciones regulares y funciones listas para producción — ahorrando días de trabajo de integración.

Explora plugins premium →

Tutoriales relacionados

Guías detalladas sobre el mismo tema.

Todos los tutoriales →

Explorar categorías de plugins

Ve directamente a las páginas de categorías de plugins en el marketplace.