Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Google Sign In with OpenID

Change variable in view

edited November 2013 in Design

I have a view that shows thumbnails of products, sorted by type. When the type changes I'd like to insert a heading showing the new type. In the past I've done this by keeping a variable like $last_type, comparing it to $current_type, and adding the new heading when they're different. In order for that to work I need, I think, to be able to change $last_type from within the view. Is there a way to do that?

Or, alternatively, is there a better way to skin this cat?

Example of what I mean ("0" = thumbnail)

Type 1
0 0 0 0 0
0 0 0 0

Type 2
0 0 0 0

Type 3
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

Comments

  • You can set a variable in a template like this (assumes a thumbnails array where each is an object with a type and src):

    {{ previous_type = null }}
    
    {% foreach thumbnails as thumb %}
        {% if thumb->type != $data->previous_type %}
            <h2>{{thumb->type}}</h2>
            {{ previous_type = $data->thumb->type }}
        {% end %}
    
        <img src="{{thumb->src}}" />
    {% end %}
    

    Another way would be to use a static variable in a function like this and use that in an {% if ... %} block:

    <?php
    
    function is_new_value ($val) {
        static $old = null;
        if ($old === $val) {
            return false;
        }
        $old = $val;
        return true;
    }
    
    ?>
    

    And the template becomes this:

    {% foreach thumbnails as thumb %}
        {% if is_new_value ($data->thumb->type) %}
            <h2>{{thumb->type}}</h2>
        {% end %}
    
        <img src="{{thumb->src}}" />
    {% end %}
    
  • Thank you!

Sign In or Register to comment.