Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse blocks of code and pass arguments to them in ExpressionEngine

Let's say I have an e-commerce site and I want to carry the way I show a product grid through numerous templates. Using the DRY principle, how would you reuse this code and potentially pass arguments into the block for some customization in different areas? Is an {embed} the best option? I could see something like that creating a lot of unnecessary overhead.

like image 817
Aaron Bushnell Avatar asked Oct 24 '12 03:10

Aaron Bushnell


2 Answers

I did this exact thing on a client site. I re-used the same product grid across the entire site and it was 100% DRY. I used the dev branch of Stash and used the new embed feature. While regular embeds are always an option that work, Stash embeds are more efficient and more powerful.

The real difference is how you pass variables, and when the embed is parsed. With stash embeds can be used inside a looping tag, and parse the data just once. (Where as regular embeds get parsed with each iteration of the loop.)

Here is a Gist I posted a while back for another user on Twitter. https://gist.github.com/2950536

Note, the example represents multiple files and code blocks, or I would just post here. IMO, it would make this post hard to follow and read if I posted it here. Essentially it follows a modified template partials approach.

More information on template partials. http://eeinsider.com/blog/ee-podcast-stash-template-partials/

But to more directly answer the question of, "How does one replace embed variables with Stash?". The solution is rather simple and based on core programming concepts of "setters" and "getters".The theory is, if one sets a variable it can be retrieved at any later point in the template. The trick is settings the variables before the getters are parsed.

{exp:stash:set}

    {stash:page_content}

        {exp:channel:entries channel="your-channel"}

            {stash:your_var_1}Some value 1{/stash:your_var_1}
            {stash:your_var_2}Some value 2{/stash:your_var_2}
            {stash:your_var_3}Some value 3{/stash:your_var_3}
            {stash:your_var_4}Some value 4{/stash:your_var_4}

            {stash:embed name="your-template" process="start"}

        {/exp:channel:entries}

    {/stash:page_content}

{/exp:stash:set}

{stash:embed name="header" process="end"}

That's where the process parameter comes into play. This will allow you to embed your template before the entries loop is ran, and to embed the header which would contain the site wrapper and output the page content. Once you get the hang of it, it becomes really powerful and makes your sites so much cleaner.

like image 193
Justin Kimbrell Avatar answered Nov 07 '22 21:11

Justin Kimbrell


You can either use embeds or possibly stash depending on what you are trying to pass.

https://github.com/croxton/Stash

like image 7
David Dexter Avatar answered Nov 07 '22 22:11

David Dexter