Skip to content

Instantly share code, notes, and snippets.

@alexroper
Created April 22, 2015 17:35
Show Gist options
  • Select an option

  • Save alexroper/29f11880e0b31536caf5 to your computer and use it in GitHub Desktop.

Select an option

Save alexroper/29f11880e0b31536caf5 to your computer and use it in GitHub Desktop.

Revisions

  1. alexroper created this gist Apr 22, 2015.
    72 changes: 72 additions & 0 deletions matrix-slideshow-example.twig
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,72 @@
    {#
    # Example of building a slideshow in Craft from adjacent matrix blocks.
    #
    # This is a technique for getting around the problem of not being able to nest
    # matrix fields. Say you're using a matrix field for your 'article-body'
    # that has rich-text fields, headings, photos with captions, and slideshows
    # all mixed together as different blocks. The slideshow is created by just placing
    # single slideshow images (with captions) next to each other in the matrix.
    #
    # For example:
    #
    # - heading
    # - text
    # - slideshowImage
    # - slideshowImage
    # - slideshowImage
    # - text
    #
    # It works by testing for the previous and next matrix block type.
    # Adjacent blocks with the same type of 'slideshowImage' get combined into
    # a single slideshow wrapper (with the class 'bxslider' since I'm using
    # the bxSlider jQuery plugin).
    #
    # The idea for prevType and nextType variables is taken from the Happy Lager
    # demo site created by Pixel and Tonic:
    # https://github.com/pixelandtonic/HappyLager/blob/master/craft/templates/_includes/article_body.html
    #
    # I know that you _could_ accomplish this by creating a single slideshow block as a list
    # of related assets and each asset entry could have a "caption" field. But, this is
    # more flexible because the caption can be specific to the context it's placed in (the article),
    # not just side wide.
    #
    -#}

    {% set prevType = null %}
    {% set nextType = null %}

    {% for block in entry.articleBody %}

    {% set type = (nextType ?: block.type.handle) %}
    {% set nextType = (not loop.last ? block.next().type.handle) %}

    {% switch type %}

    {% case 'text' %}
    {{ block.text }}

    {% case 'slideshowImage' %}
    {% if prevType != 'slideshowImage' %}
    <div class="bxslider">
    {% endif %}

    {% set asset = block.image.first() %}
    {% if asset %}
    <figure class="bxslider-item">
    <img src="{{ asset.url }}">
    <figcaption>
    {% if block.caption %}
    {{ block.caption }}<br>
    {% endif %}
    </figcaption>
    </figure>
    {% endif %}

    {% if nextType != 'slideshowImage' %}
    </div>
    {% endif %}

    {% endswitch %}

    {% set prevType = type %}
    {% endfor %}