简体   繁体   中英

Substitute variables of a template body email from database by specific information in CakePHP

Imagine this scenario, I have a table called "message_templates" with the following structure:-

id
subject
body

where the body value is:-

<p>ID: ${PROJECT_ID} </p>
<p>Project's Title: ${PROJECT_TITLE} </p>

What is the best way to substitute theses variables in CakePHP - I know it, CakeEmail has a Configuration parameter called "template" but its not the case, because my template( body column ) comes from database. Maybe use preg_replace or sprintf before send?

Somebody could help me?

You just need to use str_replace and provide an array of tokens and an array of substitutions:-

$body = str_replace(
    [
        '${PROJECT_ID}',
        '${PROJECT_TITLE}'
    ], 
    [
        '1',
        'Foo bar'
    ],
    $data['MessageTemplate']['body']
);

You can then pass $body to CakeEmail and send the email as normal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM