method for creating PHP templates (ie html with variables)?

后端 未结 6 514
北恋
北恋 2021-02-04 21:22

I\'m designing my html emails, these are to be a block of html containing variables that i can store in a $template variable.

My problem comes with the storing in the va

6条回答
  •  借酒劲吻你
    2021-02-04 21:49

    For emails, I'm a big fan of file-based templates and a really basic template parser. One advantages of this is that clients and domain experts can read and even edit the text. The other is that you're not relying on variable scope, like with heredoc. I do something like this:

    Text file with email template:

    Welcome, [Username]
    
    Thank you for creating an account.
    Please ... etc.
    

    PHP client code:

    $templateData = array ('Username'=>$username...); // get this from a db or something in practice
    $emailBody = file_get_contents ($templateFilePath);// read in the template file from above
    foreach ($templateData as $key => $value){
      $emailBody = str_replace ("[$key]", $value, $emailBody);
    }
    

    Of course, you'll be in trouble if your email needs to contain the text [Username], but you can come up with your own pseudocode convention. For html or more complicated emails with things like loops and conditions, you could extend this idea, but it's easier and safer to use a template engine. I like PHPTAL, but it refuses to do plain text.

    EDIT: For emails, you probably want a plain text version as well as an HTML version. Using functions or methods to load the files and do the substitution makes adding the second format pretty painless, though.

提交回复
热议问题