We use cookies to improve your experience. No personal information is gathered and we don't serve ads. Cookies Policy.

ExpressionEngine Logo ExpressionEngine
Features Pricing Support Find A Developer
Partners Upgrades
Blog Add-Ons Learn
Docs Forums University
Log In or Sign Up
Log In Sign Up
ExpressionEngine Logo
Features Pro new Support Find A Developer
Partners Upgrades
Blog Add-Ons Learn
Docs Forums University Blog
  • Home
  • Forums

Best Practices: Helper functions in EE

Development and Programming

Move's avatar
Move
1 posts
14 years ago
Move's avatar Move

I’m a CI developer who just started my first EE project.

Problem:

  • I have a string with spaces and mixed casing: “My String.”
  • I want to replace the spaces with hyphens and transform the string to lowercase: “my-string.”

Question:

  • What’s the preferred method for doing this in EE?

Options:

  • In PHP, this would be fairly trivial:
<?= strtolower(str_replace(' ', '-', 'My String')) ?>
  • In CI, I would probably move the above code into a helper function:
// Helper
function to_slug($str = '')
{
    return strtolower(str_replace(' ', '-', $str));
}

// View
<?= to_slug('My String') ?>
  • In EE, I know I could write a plugin to do the above, but isn’t that overkill? The result might be something like:
{exp:toslug}My String{/exp:toslug}
  • Or, what about an embed? Even that seems a bit much. Something like:
{embed="functions/to_slug" str="My String"}

What do you think?

       
Move's avatar
Move
1 posts
14 years ago
Move's avatar Move

Turns out EE plugins are simpler to write than I thought:

class View_helper {

    public $return_data = '';

    // -------------------------------------------------------------------

    public function __construct()
    {
        $this->EE =& get_instance();
        
        $param   = $this->EE->TMPL->fetch_param('helper');
        $tagdata = $this->EE->TMPL->tagdata;
        
        switch($param)
        {
            case 'to_slug':
                $this->return_data = strtolower(str_replace(' ', '-', $tagdata));
                break;
        }
    }
}
{exp:view_helper helper='to_slug'}My String{/exp:view_helper}

Still, I’m curious to hear your thoughts.

       

Reply

Sign In To Reply

ExpressionEngine Home Features Pro Contact Version Support
Learn Docs University Forums
Resources Support Add-Ons Partners Blog
Privacy Terms Trademark Use License

Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.