I’m trying to figure out what is the best way to clone/template HTML that is frequently repeated in my web app. For example, I have a voting <form> (see below) that needs to be located on several pages.
Two ways I thought of doing this:
- a function call, e.g.,
voteForm($action, $user_id, $formType, $success); - an
includestatement, e.g.,include '/myApp/views/voteForm.php'
I prefer an include statement b/c:
- Then I don’t have to decide on the function’s parameters which may change over time forcing me to rewrite the function calls everywhere they exists in my app. With the
includestatement, I can just use the variables as they are wherever I put theincluded php file (avoiding redeclaring them which is a pain b/c there are often lots of variables). - I can write the HTML in HTML and not as a PHP string where I have to deal with escaping characters/json_encode issues.
Should I reconsider using include instead function() for any reasons (e.g., performance)? Are there are other templating solutions I’m not thinking of?
<form action="<?=$action?>" method='post' data-form-data='{'formType': '<?=$formType?>', 'success': '<?=$success?>'} >`
<input type='hidden' value='<?=$user_id?>' name='user_id'>
<input type='radio' value='1' name='vote'>
<input type='radio' value='-1' name='vote'>
</form>
It’s really up to you–you could have a hybrid of a
functionthat callsincludefor you (setting up any necessary variables that the include file may need for display purposes). e.g.As far as performance, there’s no huge benefit that I’m aware of. Although If you’re looking for a better way for templating, you may want to look at smarty or some other system that handles most of the ‘tough work’ for you.
Just keep in mind that when you have code outputting HTML you no longer have a separation of concerns. That is to say that if you decide to change the look and feel of the site at a later date you’re not looking through just
.inc(or whatever extension you’ve used) files, but now both.incand.phpfiles to apply changes.