Handlebars.js: Solicitud de función: asistente de "unión" incorporado

Creado en 27 oct. 2011  ·  8Comentarios  ·  Fuente: handlebars-lang/handlebars.js

No pude encontrar una manera de usar un asistente incorporado para unir una lista de elementos con un delimitador. Si ya hay un asistente incorporado o una combinación de asistentes incorporados que pueden hacer esto, hágamelo saber. De lo contrario, le sugiero que agregue un asistente integrado llamado "unirse" que tiene un parámetro para el delimitador.

Por ejemplo, la plantilla contendría algo como esto:

 {{join myArray delimiter=", "}}

Terminé registrando mi propio ayudante para mis necesidades inmediatas:

Handlebars.registerHelper("join", function(context, block) {
     return context.join(block.hash.delimiter);
});

Esto debe modificarse para manejar casos cuando el contexto es nulo, el contexto no es una matriz, el delimitador es nulo, etc.

feature

Comentario más útil

Para nodo:

Handlebars.registerHelper( "join", function( array, sep, options ) {
    return array.map(function( item ) {
        return options.fn( item );
    }).join( sep );
});
<p>
    {{#join companies "<br>"}}
        {{name}}
    {{/join}}
</p>

Todos 8 comentarios

Acabo de hacer esto para mí hoy:

Handlebars.registerHelper('join', function(val, delimiter, start, end) { 
    return [].concat(val).slice(start, end).join(delimiter); 
});

Si val no es una matriz, tiene el efecto de simplemente devolver val. Los parámetros 2.º a 4.º son totalmente opcionales (el delimitador predeterminado es ","). Solo he probado en Chrome hasta ahora.

Actualización: esto se rompe en IE8. [...].slice(undefined, undefined) devuelve una matriz vacía en lugar de la matriz completa como en otros navegadores. Además, si no proporciona un delimitador en la definición de su plantilla, Handlebars pasa el objeto hash como delimitador, que IE representa como '[Objeto]' en lugar de una coma como otros navegadores. Mi versión revisada se ve así:

Handlebars.registerHelper('join', function(val, delimiter, start, end) {
    var arry = [].concat(val);
    delimiter = ( typeof delimiter == "string" ? delimiter : ',' );
    start = start || 0;
    end = ( end === undefined ? arry.length : end );
    return arry.slice(start, end).join(delimiter); 
});

No es tan concisamente elegante, pero verificar la cordura de sus entradas es probablemente una buena práctica.

--Chad

He incorporado las sugerencias de ceberle:

//Handlebars "join" block helper that supports arrays of objects or strings.  
//If "delimiter" is not speficified, then it defaults to ",".  You can use "start", 
//and "end" to do a "slice" of the array.

Handlebars.registerHelper('join', function(items, block) {
    var delimiter = block.hash.delimiter || ",", 
        start = start = block.hash.start || 0, 
        len = items ? items.length : 0,
        end = block.hash.end || len,
        out = "";

        if(end > len) end = len;

    if ('function' === typeof block) {
        for (i = start; i < end; i++) {
            if (i > start) out += delimiter;
            out += block(items[i]);
            if('string' === typeof items[i])
                out += items[i];
            else
                out += block(items[i]);
        }
        return out;
    } else { 
        return [].concat(items).slice(start, end).join(delimiter);
    }
});

Vaya, quise quitar una línea:

//Handlebars "join" block helper that supports arrays of objects or strings.  
//If "delimiter" is not speficified, then it defaults to ",".  You can use "start", 
//and "end" to do a "slice" of the array.

Handlebars.registerHelper('join', function(items, block) {
    var delimiter = block.hash.delimiter || ",", 
        start = start = block.hash.start || 0, 
        len = items ? items.length : 0,
        end = block.hash.end || len,
        out = "";

        if(end > len) end = len;

    if ('function' === typeof block) {
        for (i = start; i < end; i++) {
            if (i > start) 
                out += delimiter;
            if('string' === typeof items[i])
                out += items[i];
            else
                out += block(items[i]);
        }
        return out;
    } else { 
        return [].concat(items).slice(start, end).join(delimiter);
    }
});

@jlubean : ¿qué versión de manillar estás usando? No puedo hacer que funcione con hasta beta 4. Recibo el siguiente error cuando uso una sintaxis como:

{{join list_of_words delimiter=","}}

El error:

Uncaught Error: Parse error on line 35:
..._of_words delimiter=&quot;,&quot;}}</tex
-----------------------^
Expecting 'STRING', 'INTEGER', 'BOOLEAN', 'ID'

Estaba usando beta 3. Eche un vistazo a mi ejemplo de trabajo en http://jsfiddle.net/jlubean/YS3EV/

Escribí esto: http://mametipsum.herokuapp.com/. Prefiero no requerir que las personas tengan que especificar un ayudante como este (consulte la pestaña "Plantilla"). Me gustaría mantenerlo simple. Me gustaría que los espacios sean los predeterminados al imprimir una matriz. Estoy feliz de anular el asistente de matriz predeterminado, pero ¿cómo lo hago? Gracias.

Personalmente, creo que es mejor mantener el manubrio simple. Si a alguien le gustaría armar un repositorio/esencial con ayudantes útiles, entonces probablemente podríamos vincularlo o resaltarlo.

Para nodo:

Handlebars.registerHelper( "join", function( array, sep, options ) {
    return array.map(function( item ) {
        return options.fn( item );
    }).join( sep );
});
<p>
    {{#join companies "<br>"}}
        {{name}}
    {{/join}}
</p>
¿Fue útil esta página
0 / 5 - 0 calificaciones