Search code examples
phphtmlcakephpcode-reusereusability

cakephp element parameters with html


I want to render a cakephp element which contains static text. The element is supposed to contain help, text, images, ... etc. but it should show only the content relevant to the current page being rendered.

I thought of two ways, one of them is to simply pass html content as a parameter from the view as follows:

echo $this->element('help-bar-content', array(
    'title' => 'Element title',
    'help_text'=> '<div>
            A lot of text and tags go here.
            <br/>
            <img class="img-class" src="/img/location"/>
            </div>'
        ));

But it is ugly because it would mix html inside php which is inside html. The second way is to have a lot of elements each of them corresponding to a help_text parameter and use them as follows:

echo $this->element('help-bar-content', array(
    'title' => 'Element title',
    'help_text'=> element('help_element1')));

Which I think is better, But then I would have a LOT of non-reusable elements because I have a lot of views.

Is there a third (better) way to do this?


Solution

  • Put all the help texts in a switch statement or multiple ifs inside the element and give each one a string as identifier and pass that string to the element. Then display the text conditionally based on that string.

    <?php if ($helpText === 'foo') : ?>
    <p>foo</p>
    <?php endif; ?>
    

    Note $helpText follows the convention while $help_text doesnt.