Nunjucks links y snippets

Este post se publicó hace más de dos años, es posible que la información publicada esté obsoleta o las referencias no existan.

Estoy migrando un proyecto de wordpress a 11ty y en esta ocasión estoy usando nunjucks para maquetar las plantillas.

You've been looking for a more sophisticated templating engine for JavaScript. Here it is.

Snippets

Recopilación de snippets.

Variables

{% set my_variable = false %}
{% if my_variable != true %}
	This statement is valid.
{% endif %}

Capture variables:

{% capture my_variable %}
    I am being captured.{% endcapture %}
{{ my_variable }}

Condicionales

{% if post.data.thumbnail %}
  <img src="{{ post.data.thumbnail }}" />
{% else %}
  <img src="no-image.png" />
{% endif %}

Loops

<ul>
    {%- for post in collections.all -%}
        <li>{{ post.data.title }}</li>
    {%- endfor -%}
</ul>

Repite dos veces el "item"

{% for i in range(0, 2) %}
    <p>Item {{ i }}</p>
{% endfor %}

Con loop.index contamos cada elemento del loop y con loop.length el total de itineraciones del loop

{%- for post in collections.all -%}
  <li>
    {{ loop.index }} / {{ loop.length }} <br />
    {{ post.data.title }}
  </li>
{%- endfor -%}

Los 5 últimos items

<ul class="beer-card__list">
  {%- for post in collections.beer | reverse -%}           
     {% if loop.index < 6 %}                
       <h3 class="beer-card__title">
         {{ post.data.title }}
       </h3>
     {% endif %}
  {%- endfor -%}
</ul>

For loop colección con tag

<ul>
  {%- for post in collections.posts -%}
    <li>
        <a href="{{ post.url }}">{{ post.data.title }}</a>    
     </li>
     tags: 
     {%- for tag in post.data.tags -%}
       {{ tag }};
     {%- endfor -%}
  {%- endfor -%}
</ul>

Includes

{% include "partials/nav-main.njk" %}
{% include "assets/images/ico.svg" %}

Comentarios

{# Comentario #}

Filtros

Replace:

<img src="{{ post.data.thumbnail | replace("150x150", "300x300") }}" width="300" height="300" />

Slug:

{{ post.data.title | slug }}

Url:

{{ pages.data.permalink | url }}

Uppercase:

{{ pages.data.title | upper }}

Random

{{ range(100000, 999999) | random  }}