2011-12-18 16 views
31

Estoy usando bigote. Estoy generando una lista de notificaciones. Un objeto de notificación JSON se parece a:¿Cómo se maneja una DECLARACIÓN DE IF en una plantilla de bigote?

[{"id":1364,"read":true,"author_id":30,"author_name":"Mr A","author_photo":"image.jpg","story":"wants to connect","notified_type":"Friendship","action":"create"}] 

Con bigote, ¿cómo puedo hacer una declaración o afirmación caso si se basa en la acción notified_type & ...

Si notified_type == "Amistad" render .. ....

Si notified_type == "Otros & & acción == "invitar" rendir .....

¿Cómo funciona eso?

+1

Posible duplicado de [¿Cómo puedo lograr un if/else en mustache.js?] (http://stackoverflow.com/questions/6027525/how-do-i-accomplish-an- if-else-in-bigote-js) – bjornte

Respuesta

43

Las plantillas de bigote son, por diseño, muy simples; el homepage incluso dice:

Plantillas sin lógica.

lo tanto, el enfoque general es hacer su lógica en JavaScript y establecer un grupo de banderas:

if(notified_type == "Friendship") 
    data.type_friendship = true; 
else if(notified_type == "Other" && action == "invite") 
    data.type_other_invite = true; 
//... 

y luego en su plantilla:

{{#type_friendship}} 
    friendship... 
{{/type_friendship}} 
{{#type_other_invite}} 
    invite... 
{{/type_other_invite}} 

Si quieres algo más avanzado funcionalidad, pero desea mantener la mayor parte de la simplicidad de Moustache, puede consultar Handlebars:

El manillar proporciona la potencia necesaria para permitirle crear plantillas semánticas de manera efectiva y sin frustración.

Las plantillas de bigote son compatibles con los manubrios, por lo que puede tomar una plantilla de bigote, importarla en manubrios y comenzar a aprovechar las funciones adicionales de los manubrios.

27

En general, se utiliza la sintaxis #:

{{#a_boolean}} 
    I only show up if the boolean was true. 
{{/a_boolean}} 

El objetivo es mover tanto la lógica como sea posible fuera de la plantilla (que tiene sentido).

7

Tengo un truco simple y genérico para realizar la declaración key/value if en lugar de boolean-only en bigote (¡y de una manera extremadamente legible!):

function buildOptions (object) { 
    var validTypes = ['string', 'number', 'boolean']; 
    var value; 
    var key; 
    for (key in object) { 
     value = object[key]; 
     if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) { 
      object[key + '=' + value] = true; 
     } 
    } 
    return object; 
} 

Con este truco, un objeto como éste:

var contact = { 
    "id": 1364, 
    "author_name": "Mr Nobody", 
    "notified_type": "friendship", 
    "action": "create" 
}; 

se parecerá a esto antes de la transformación:

var contact = { 
    "id": 1364, 
    "id=1364": true, 
    "author_name": "Mr Nobody", 
    "author_name=Mr Nobody": true, 
    "notified_type": "friendship", 
    "notified_type=friendship": true, 
    "action": "create", 
    "action=create": true 
}; 

Y su plantilla bigote se verá así:

{{#notified_type=friendship}} 
    friendship… 
{{/notified_type=friendship}} 

{{#notified_type=invite}} 
    invite… 
{{/notified_type=invite}} 
+0

Esto abota los datos del bigote, pero es utilizable y r un enfoque legible que vale la pena considerar – SketchBookGames

+1

¡El ejemplo de igualdad es realmente útil! – JeanValjean

37

Acabo de tomar una mirar por encima de los documentos bigote y apoyan "protuberancias invertidas" en la que se declaran

ellos (protuberancias invertidas) se brindará si no existe la clave, es falso, o es una lista vacía

http://mustache.github.io/mustache.5.html#Inverted-Sections

{{#value}} 
    value is true 
{{/value}} 
{{^value}} 
    value is false 
{{/value}} 
+2

¡Excelente trabajo para mostrar cómo hacerlo si es cierto, y también hacer lo falso! – Triforcey

Cuestiones relacionadas