Plugin lanzando TypeError después de Wordpress 4.5 actualización


Estoy depurando un plugin visual composer que se rompió después de actualizar Wordpress a 4.5 y no puedo entender por qué está lanzando un TypeError.

El mensaje de error en la consola:

JQMIGRATE: Migrate is installed, version 1.4.0              load-scripts.php?....
Uncaught TypeError:     $template.get is not a function     composer-view.js?ver=4.1.1.1:73

Las únicas ocurrencias de $template se encuentran en el siguiente código. Entiendo que esto no es mucho contexto para salir de, pero, ¿cómo puedo resolver este error?

/**
 * Convert html into correct element
 * @param html
 */
html2element: function(html) {
  var attributes = {},
    $template;
  if (_.isString(html)) {
    this.template = _.template(html);
    $template = $(this.template(this.model.toJSON()).trim());
  } else {
    this.template = html;
    $template = html;
  }
  _.each($template.get(0).attributes, function(attr) { // **errors on this line**
    attributes[attr.name] = attr.value;
  });
  this.$el.attr(attributes).html($template.html());
  this.setContent();
  this.renderContent();
},


Actualización:

Parece que esto podría ser un problema con jQuery. Wordpress 4.5 incluye jQuery 1.12 que corrigió un error que permitía ejecutar cierto código con sintaxis incorrecta. Asumo que el código del complemento debe haber tenido una sintaxis incorrecta, pero se ejecutó sin embargo hasta ahora.

Https://wordpress.org/support/topic/read-this-first-wordpress-45-master-list#post-8271654

Author: spencer.sm, 2016-04-13

10 answers

Pude resolver el problema. Resulta que estaba usando una versión anterior de JS composer. La actualización a la versión más reciente rompió mi sitio, así que rastreé el error y actualizé la función html2element a

html2element: function(html) {
            var $template, attributes = {},
                template = html;
            $template = $(template(this.model.toJSON()).trim()), _.each($template.get(0).attributes, function(attr) {
                attributes[attr.name] = attr.value
            }), this.$el.attr(attributes).html($template.html()), this.setContent(), this.renderContent()
        },

Todo está funcionando bien para mí otra vez! Espero que esto ayude a otros.

 115
Author: Ben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-15 19:04:18

Todavía estaba recibiendo este error después de probar el parche en la respuesta de Ben: Uncaught TypeError: Cannot read property' custom ' of undefined

Así que modifiqué el html2element en composer-view.js as follows:

 html2element: function(html) {
        var $template, attributes = {},
            template = html;

        $template = $(template(this.model.toJSON()).trim());
        if($template.get(0))
        {
            _.each($template.get(0).attributes, function(attr) {
            attributes[attr.name] = attr.value
        })};

        this.$el.attr(attributes).html($template.html()),
        this.setContent(),
        this.renderContent()
    },
 31
Author: ECC-Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-20 16:24:39

@Ben Esto funciona perfecto!

Causa: El administrador no estaba cargando el editor visual correcto para el complemento js_composer después de actualizar estos complementos.

=====================================================

Error:

Error: TypeError: template template.get no es una función Archivo fuente: wp-content/plugins/js_composer_salient/assets/js/dist / backend.min.js?ver = 4,10 Alinear: 4047

=====================================================

Solución Goto file / wp-content/plugins/js_composer_salient/assets/js/dist / backend.min.js alrededor de la línea 4045:

======> Reemplace el código =====================================================

    html2element: function(html) {
        var $template, attributes = {};
        _.isString(html) ? (this.template = _.template(html), $template = $(this.template(this.model.toJSON(), vc.templateOptions["default"]).trim())) : (this.template = html, $template = html), _.each($template.get(0).attributes, function(attr) {
            attributes[attr.name] = attr.value
        }), this.$el.attr(attributes).html($template.html()), this.setContent(), this.renderContent()
    },

======> Reemplazar con este código ========================================

    html2element: function(html) {
        var $template, attributes = {},
        template = html;
        $template = $(template(this.model.toJSON()).trim()), _.each($template.get(0).attributes, function(attr) {
                attributes[attr.name] = attr.value}), 
                this.$el.attr(attributes).html($template.html()), this.setContent(), 
                this.renderContent()
    },
 18
Author: Didierh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-19 15:01:56

Estoy usando el tema Applay (2.1.3, un poco desactualizado). Acabo de actualizar WP y todos los complementos a la versión más reciente (4.5.2) y llegué a este problema también. No analicé el flujo de este componente (js_composer), solo esta función "rota" (no está realmente rota). Me di cuenta de que esto.template y template template están obteniendo tipos de objetos incorrectos (necesita otra validación aparte _.isString(html)). Lo resolví agregando un bloque try & catch como sigue:

ORIGINAL

    html2element:function (html) {
        var attributes = {}, 
            $template;
        if (_.isString(html)) {
            this.template = _.template(html);
            $template = $(this.template(this.model.toJSON()).trim());
        } else {
            this.template = html;                                                                                                                                            
            $template = html;
        }
        _.each($template.get(0).attributes, function (attr) {
            attributes[attr.name] = attr.value;
        }); 
        this.$el.attr(attributes).html($template.html());
        this.setContent();
        this.renderContent();
    },

MODIFICADO

    html2element:function (html) {
        var attributes = {}, 
            $template;
        if (_.isString(html)) {
            this.template = _.template(html);
        } else {
            try {
                this.template = _.template(html());                                                                                                                          
            } catch (err) {
                this.template = html;
            }   
        }   
        $template = $(this.template(this.model.toJSON()).trim());
        _.each($template.get(0).attributes, function (attr) {
            attributes[attr.name] = attr.value;
        }); 
        this.$el.attr(attributes).html($template.html());
        this.setContent();
        this.renderContent();
    },
 4
Author: Luciano Fantuzzi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-08 16:00:23

Notó que el código no se estaba pasando a la función html2element, pero sí existía en la función que la llamaba (render)

El siguiente código ha corregido completamente mis problemas, puedo cargar la página, agregar, clonar, eliminar, etc

render: function () {
			var $shortcode_template_el = $( '#vc_shortcode-template-' + this.model.get( 'shortcode' ) );
			if ( $shortcode_template_el.is( 'script' ) ) {
				var newHtmlCode =  _.template( $shortcode_template_el.html(),
												this.model.toJSON(),
												vc.templateOptions.default );
				if(!_.isString(newHtmlCode)){
					newHtmlCode = $shortcode_template_el.html();
				}
				this.html2element( newHtmlCode );
			} else {
				var params = this.model.get( 'params' );
				$.ajax( {
					type: 'POST',
					url: window.ajaxurl,
					data: {
						action: 'wpb_get_element_backend_html',
						data_element: this.model.get( 'shortcode' ),
						data_width: _.isUndefined( params.width ) ? '1/1' : params.width,
						_vcnonce: window.vcAdminNonce
					},
					dataType: 'html',
					context: this
				} ).done( function ( html ) {
					this.html2element( html );
				} );
			}
			this.model.view = this;
			this.$controls_buttons = this.$el.find( '.vc_controls > :first' );
			return this;
		},
 4
Author: Amritosh pandey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-10 12:54:30

Estoy usando el tema Astra. Esta solución funciona en un 99,9%. Para algunos tho, esto solo detiene la rueda giratoria, pero una vez que la página carga visual composer no lo hace.

Hice un pequeño cambio en este código (que está publicado en todas partes por ahora)

Código de tema original de Astra aquí (composer-view.js)

        html2element:function (html) {
        var attributes = {},
            $template;
        if (_.isString(html)) {
            this.template = _.template(html);
            $template = $(this.template(this.model.toJSON()).trim());
        } else {
            this.template = html;
            $template = html;
        }
        _.each($template.get(0).attributes, function (attr) {
            attributes[attr.name] = attr.value;
        });
        this.$el.attr(attributes).html($template.html());
        this.setContent();
        this.renderContent();
    },

El código que funciona :

html2element: function(html) {
    var $template, 
    attributes = {},
    template = html;
    $template = $(template(this.model.toJSON()).trim()), 
     _.each($template.get(0).attributes, function(attr) {
    attributes[attr.name] = attr.value
}); this.$el.attr(attributes).html($template.html()), this.setContent(), this.renderContent()

},

La diferencia principal se encuentra aquí (frente al código original)

}); this.$el.attr

Hay un punto y coma en lugar de la coma original:):

}), this.$el.attr

Saludos a la gente:) Así que

 3
Author: Renegade_Mtl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-28 21:22:14

Bueno, encontré la solución en este sitio: https://wordpress.org/support/topic/visual-composer-is-not-working

Primero: editar html2element:.... en in / wp-content/plugins/js_composer/assets/js/backend / composer-view.js

html2element: function(html) {
        var $template, attributes = {},
            template = html;
        $template = $(template(this.model.toJSON()).trim()), _.each($template.get(0).attributes, function(attr) {
            attributes[attr.name] = attr.value
        }), this.$el.attr(attributes).html($template.html()), this.setContent(), this.renderContent()},

Segundo: Sin embargo, si abre el editor de frontend, tendrá este problema de "recortar" en custom_views.js: 101, y la línea 467 de otro archivo. Olvidé el nombre, pero creo que puede ser frontend_editor.js.

Editar en: \wp-content \ plugins \ js_composer \ assets \ js \ frontend_editor \

  • frontend_editor.js
  • custom_views.js

Código incorrecto:

this.$controls = $( _.template( template, data, _.extend( {},
            vc.template_options,
            { evaluate: /\{#([\s\S]+?)#}/g } ) ).trim() ).addClass( 'vc_controls' );

Código fijo:

this.$controls = $( _.template( template, data, _.extend( {},
            vc.template_options,
            { evaluate: /\{#([\s\S]+?)#}/g } ) )().trim() ).addClass( 'vc_controls' );

Tercero: Ver la magia negra.

Saludos.

 1
Author: Sebastian Diaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-23 05:43:34

Checkout debajo del código para ambos template template.get no es una función y Uncaught TypeError: No puede leer la propiedad 'attributes' de undefined. Funcionó para mí.

html2element: function(html) {
    var $template, attributes = {},
            template = html;

        $template = $(template(this.model.toJSON()).trim());
        if($template.get(0))
        {
            _.each($template.get(0).attributes, function(attr) {
            attributes[attr.name] = attr.value
        })};

        this.$el.attr(attributes).html($template.html()),
        this.setContent(),
        this.renderContent()
}
 1
Author: Amit Garg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-18 18:26:37

Hice esta modificación que funciona en mi WP 4.8.1 (PHP7)

En el archivo wp-content/plugins/js_composer/assets/js/backend/composer-view.js

Debe modificar el método render :

Reemplace esta línea

this.html2element(_.template($shortcode_template_el.html(), this.model.toJSON())); 

Por esta línea

this.html2element( $shortcode_template_el.html() );

Parece el _.función template () que no funciona perfectamente y no devuelve el objeto bueno, así que es mejor dar el código html en su lugar.

 1
Author: sly63,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-03 22:45:09

Intenta actualizar tu tema. Ir a Apariencia>Temas, y comprobar si hay una actualización. Esto resolvió el problema automáticamente tras la actualización.

El error surge cuando actualizas a WP 4.5 para mí ejecutando el tema Nimva. Usted tiene que actualizar a 2.02 de Nimva, que permite actualizaciones automáticas.

 0
Author: Robert Spencer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-15 15:59:18