Web
Article

By Rynoguill

thanks david, keep these tips coming!

Meet the author
  • http://www.delyrical.com davidjmedlock

    …posted by davidjmedlock:

    So, a couple of weeks ago I posted Code Reuse Part One and gave a brief tutorial on custom tags. Today I’ll talk a bit about encapsulation and returning variables.

    Encapsulation, or “black boxing”, refers to a programming methodology often used in Obect Oriented Programming. The concept behind it is that you keep all the logic in your custom tag hidden from the template that is calling it. Custom tags have some level of natural encapsulation in that the variables you create inside the custom tag (local variables) are not available to the calling template.

    If this is the case, though, how can you “return” a variable from a custom tag? Well, there is a struct available within custom tags and modules called “Caller”. This struct contains all the variables that are available in the calling template. So for example, let’s say I create a template like this:




    (We’re using the custom tag from part one.) In this case, if we modify the custom tag to look like this:




    #Attributes.Hello#

    #letter#

    In this case, we’d get an error because the variable “letter” is not available. But let’s say we change that line to:


    #Caller.letter#

    Now it works like a charm. Similarly, we can set variables in the caller struct. So if we do this inside the custom tag:



    Then we modify our template to look like this:




    #letter2#

    In this case it will work just fine because we can easily modify the Caller struct.

    So there’s a quick and dirty run down on returning variables from a custom tag. There’s much, much more to custom tags, so maybe we’ll cover that in the future. ‘Til next time, happy coding!

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Front-end, once a week, for free.