假设我们必须管理用户登录和注销。
我们有一个index.php文件,默认情况下显示索引。Twig模板(包含一个头文件,允许用户登录或注册。
我们有另一个类似index的Twig模板(welcome.twig)。小枝模板,但是,它的头显示访问用户配置文件,注销选项和操作,我们的用户可以在网站上做。
我想知道如果index.php文件可以显示这两个模板中的一个条件。
在我的index.php文件中,我得到了这个:
if (!isset($_SESSION['account'])){
$twig->display("index.twig");
}else{
$twig->display("welcome.twig");
}
你可能知道,我正在告诉显示索引。twig(默认模板)当帐户未设置在$_SESSION变量中,并显示欢迎。在$_SESSION变量中设置account
$_SESSION变量上的帐户设置发生在其他名为login.php的文件
现在,我一直在使用第二个文件(welcome.php)来获得我想要的东西,但我不确定这是一个好方法…
谢谢。
应该在模板上使用条件继承。看看这个答案:
在条件
上扩展模板你可以传递一个变量给模板,像这样:
$twig->display("index.twig", array('logged' => isset($_SESSION['account'])));
然后,使用该变量在模板中执行条件。它可以从两个模板继承,每个模板都有不同的菜单,这取决于用户是否登录。
我遇到了这样一个解决方案:
我为index.php文件中的$_SESSION变量设置了一个值
<?php
require_once '../vendor/autoload.php';
require_once '../generated-conf/config.php';
require_once '../vendor/twig/twig/lib/Twig/Autoloader.php';
session_start(); // Session always starts when index.php is loaded (even if it is loaded for the first time)
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('templates/');
$twig = new Twig_Environment($loader);
// Condition to show any or other template
if (isset($_SESSION['online']) && ($_SESSION['online'] == true)){
$args= array('online' => true, 'session' => $_SESSION);
}else{
$args= array('online' => false);
}
// Display Twig template
$twig->display("index.twig", $args);
?>
在我的Twig模板(index.twig)中:
{% if online == true %} {# It's not the $_SESSION variable 'online' value, but the 'online' value of the 'args' array #}
{% include 'userMenu.twig' %}
{% else %}
{% include 'defaultMenu.twig' %}
{% endif %}
这是使它工作:)
希望对大家有所帮助。