简体   繁体   English

从模板执行php代码

[英]Execute php code from template

I have the following code in PHP: 我在PHP中有以下代码:

if ($maintenance_mode == true)
{
    $file = 'maintenance-header.php';
    $template = file_get_contents($t_includes_path . $file);
}
else
{
    $file = 'main-header.php';
    $template = file_get_contents($t_includes_path . $file);
}

require_once($s_system_path . 'templater.php');

And then in templater.php : 然后在templater.php

$page = str_replace(array(
    '{slang}',
    '{site_title}',
    '{site_desc}',
    '{keywords}',
    '{t_assets_path}',
    '{s_assets_path}',
    '{i_assets_path}',
    ), array(
    $slang,
    $site_title,
    $site_content,
    $keywords,
    $t_assets_path,
    $s_assets_path,
    $i_assets_path,
    ),
    $template);
echo $page;

The problem is that if I try to use php code within the template file itself it doesn't get recognized and is parsed as comments/plain text. 问题是,如果我尝试在模板文件本身中使用php代码,它将不会被识别,而是被解析为注释/纯文本。 Example: 例:

if (htmlentities($_GET['lang'], ENT_QUOTES) == 'en')
{
    echo 'English';
}
else if (htmlentities($_GET['lang'], ENT_QUOTES) == 'ru')
{
    echo 'Russian';
}
else
{
    echo 'Other';
}

How to deal with this? 该如何处理? I really want to use {site_title} instead of <?php echo $site_title; ?> 我真的很想用{site_title}代替<?php echo $site_title; ?> <?php echo $site_title; ?> etc. I want to keep my code as clean as possible. <?php echo $site_title; ?>等。我想保持代码尽可能整洁。

you have to exectue your php code. 你必须exectue您的PHP代码。 if you just 'echo' it, code that is inside your string will not be executed, just printed on the page. 如果您只是“回显”它,则仅打印在页面上,不会执行字符串内部的代码。 you can use eval() function for example, but be sure that users can't force your web to eval() theirs code.. as mentioned on docs: 例如,您可以使用eval()函数,但请确保用户不能强迫您的网站将eval()的代码..如文档中所述:

http://php.net/manual/en/function.eval.php http://php.net/manual/zh/function.eval.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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