symfony模板

2021-06-13  本文已影响0人  追梦人在路上不断追寻

symfony默认的模板是twig,这是一个便携,高效,安全的模板引擎。

Twig

twig是非常简洁的php模板引擎,它非常类似于JavaScript的juicer模板引擎,你可以在模板中实现条件的判断。

twig中不能运行php代码,但是我们可以通过过滤器来修改渲染内容,比如filter来让内容编程大写。

模板的配置

auto_reload:用来配置模板是否自动重新渲染,如果设置为true,那么当源码被修改的时候,它会重新编译模板文件。

autoescape:用来配置过滤那些标签,比如html,css,js等。

cache:配置模板编译缓存

debug:是否开启调试

创建模板

在templates文件夹中创建模板文件

{# templates/user/notifications.html.twig #}
<h1>Hello {{ user_first_name }}!</h1>
<p>You have {{ notifications|length }} new notifications.</p>

静态资源的引入

在twig中,可以通过asset方法引入静态资源css,js,image等。

 composer require symfony/asset
{# the image lives at "public/images/logo.png" #}
<img src="{{ asset('images/logo.png') }}" alt="Symfony!"/>

{# the CSS file lives at "public/css/blog.css" #}
<link href="{{ asset('css/blog.css') }}" rel="stylesheet"/>

{# the JS file lives at "public/bundles/acme/js/loader.js" #}
<script src="{{ asset('bundles/acme/js/loader.js') }}"></script>

模板的嵌套和继承

{{ include('blog/_user_profile.html.twig') }}
{# templates/base.html.twig #}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}My Application{% endblock %}</title>
        {% block stylesheets %}
            <link rel="stylesheet" type="text/css" href="/css/base.css"/>
        {% endblock %}
    </head>
    <body>
        {% block body %}
            <div id="sidebar">
                {% block sidebar %}
                    <ul>
                        <li><a href="{{ path('homepage') }}">Home</a></li>
                        <li><a href="{{ path('blog_index') }}">Blog</a></li>
                    </ul>
                {% endblock %}
            </div>

            <div id="content">
                {% block content %}{% endblock %}
            </div>
        {% endblock %}
    </body>
</html>
上一篇下一篇

猜你喜欢

热点阅读