set标签
主要是用来给变量赋值的。
{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
{% set foo = 'foo' ~ 'bar' %}
{% set foo, bar = 'foo', 'bar' %}
{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
{% set foo = 'foo' ~ 'bar' %}
{% set foo, bar = 'foo', 'bar' %}
其中 'foo'~'bar' 这个我没怎么看明白,测试了一下,可能是字符串连接的。
set还有一种用法,就是把 块内的内容赋值给变量
{% set foo %}
...
{% endset %}
{% set foo %}
...
{% endset %}
extends标签
这个标签用来表示本模板继承自另外一个模板。和php一样,twig不支持多重继承,所以你只能有一个extends标签,而且要在模板的最上方。
我们先来定义一个“基模板” base.html 他就像一个骨架一个。
{% block head %}
{% endblock %}
{% block head %}
{% endblock %}
{% block %}标签定义了4个区块(block head, block title, block content, block footer),可以让子模板来填充内容。block的作用就是告诉模板引擎,这里面的内容可以被子模板覆盖。
一个子模板大概类似于这样的
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ parent() }}
{% endblock %}
{% block content %}
Index
Welcome on my awesome homepage.
{% endblock %}
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ parent() }}
{% endblock %}
{% block content %}
Index
Welcome on my awesome homepage.
{% endblock %}
extends是非常关键的,它告诉模板引擎,本模板继承自另一个模板(base.html)。当模板引擎解析到本模板时,会首先载入父模板。extends标签应该是模板内的第一个标签。
如果子模板没有定义block footer ,那么父模板会用默认值代替。
注意:block标签的名字是不能重复的。如果你想让同一个block多次打印。可以使用block函数
{{ block('title') }}
{% block body %}{% endblock %}
{{ block('title') }}
{% block body %}{% endblock %}
父block
也许你会需要 父block的内容。可以使用parent函数,这很有用比如你想往一个block里添加内容而不是覆盖时。
{% block sidebar %}
Table Of Contents
...
{{ parent() }}
{% endblock %}
{% block sidebar %}
Table Of Contents
...
{{ parent() }}
{% endblock %}
命名endblock
模板引擎 允许你命名结束标记,这样可读性会提高很多。但个人觉得没啥用处。
{% block sidebar %}
{% block inner_sidebar %}
...
{% endblock inner_sidebar %}
{% endblock sidebar %}
{% block sidebar %}
{% block inner_sidebar %}
...
{% endblock inner_sidebar %}
{% endblock sidebar %}
嵌套block
允许你嵌套生成block ,来形成更复杂的block
{% for item in seq %}
{% endfor %}
{% for item in seq %}
{% endfor %}
简写block
以下这两种写法是等效的
{% block title %}
{{ page_title|title }}
{% endblock %}
{% block title page_title|title %}
{% block title %}
{{ page_title|title }}
{% endblock %}
{% block title page_title|title %}
动态继承
你可以用一个变量来继承不同的模板。
{% extends some_var %}
{% extends some_var %}
如果变量是一个twig模板对象,也可以。
$layout = $twig->loadTemplate('some_layout_template.twig');
$twig->display('template.twig', array('layout' => $layout));
$layout = $twig->loadTemplate('some_layout_template.twig');
$twig->display('template.twig', array('layout' => $layout));
1.2版本更新 你可以传递一个数组,twig会选择第一个存在的模板,来继承。
{% extends ['layout.html', 'base_layout.html'] %}
{% extends ['layout.html', 'base_layout.html'] %}
条件继承
这个很简单自己看吧,
{% extends standalone ? "minimum.html" : "base.html" %}
{% extends standalone ? "minimum.html" : "base.html" %}
block标签
参见 extends标签
include标签
载入一个模板,返回渲染的内容。载入的模板可以使用当前模板的变量{% include 'header.html' %}
Body
{% include 'footer.html' %}
{% include 'header.html' %}
Body
{% include 'footer.html' %}
你可以给模板添加变量
{# the foo template will have access to the variables from the current context and the foo one #}
{% include 'foo' with {'foo': 'bar'} %}
{% set vars = {'foo': 'bar'} %}
{% include 'foo' with vars %}
{# the foo template will have access to the variables from the current context and the foo one #}
{% include 'foo' with {'foo': 'bar'} %}
{% set vars = {'foo': 'bar'} %}
{% include 'foo' with vars %}
你也可以使用 only 关键字 来禁止载入的模板使用当前模板的变量,只能使用include 时with的变量{# only the foo variable will be accessible #}
{% include 'foo' with {'foo': 'bar'} only %}
{# no variable will be accessible #}
{% include 'foo' only %}
{# only the foo variable will be accessible #}
{% include 'foo' with {'foo': 'bar'} only %}
{# no variable will be accessible #}
{% include 'foo' only %}
载入的模板名也可以是一个twig表达式
{% include some_var %}
{% include ajax ? 'ajax.html' : 'not_ajax.html' %}
{% include some_var %}
{% include ajax ? 'ajax.html' : 'not_ajax.html' %}
也可以用twig模板对象
$template = $twig->loadTemplate('some_template.twig');
$twig->loadTemplate('template.twig')->display(array('template' => $template));
$template = $twig->loadTemplate('some_template.twig');
$twig->loadTemplate('template.twig')->display(array('template' => $template));
1.2版本新加内容,可以在模板加上 ignore missing 关键字,这样当模板不存在的时候就不会引发错误。
{% include "sidebar.html" ignore missing %}
{% include "sidebar.html" ignore missing with {'foo': 'bar} %}
{% include "sidebar.html" ignore missing only %}
{% include "sidebar.html" ignore missing %}
{% include "sidebar.html" ignore missing with {'foo': 'bar} %}
{% include "sidebar.html" ignore missing only %}1.2版本新加内容,你可以给include传递一个数组,他会自动载入第一个存在的模板{% include ['page_detailed.html', 'page.html'] %}
{% include ['page_detailed.html', 'page.html'] %}
import 标签
twig允许把一些常用的代码放入到macros(宏)里,这些macros被不同的模板导入。
有两种方法导入模板,你可以导入整个模板到一个变量里,或者只导入需要的几个macros
假如我们有个助手模块,来帮助我们渲染表单(forms.html)
{% macro input(name, value, type, size) %}
{% endmacro %}
{% macro textarea(name, value, rows) %}
{% endmacro %}
{% macro input(name, value, type, size) %}
{% endmacro %}
{% macro textarea(name, value, rows) %}
{% endmacro %}
最简单,最灵活的办法就是导入整个模板。(把模板导入到 forms变量里)
{% import 'forms.html' as forms %}
- Username
- {{ forms.input('username') }}
- Password
- {{ forms.input('password', null, 'password') }}
{{ forms.textarea('comment') }}
{% import 'forms.html' as forms %}
- Username
- {{ forms.input('username') }}
- Password
- {{ forms.input('password', null, 'password') }}
{{ forms.textarea('comment') }}
或者你可以导入模板的名字到当前的名字空间下。 (导入input,textarea 并把input重名为input_field)
{% from 'forms.html' import input as input_field, textarea %}
- Username
- {{ input_field('username') }}
- Password
- {{ input_field('password', '', 'password') }}
{{ textarea('comment') }}
{% from 'forms.html' import input as input_field, textarea %}
- Username
- {{ input_field('username') }}
- Password
- {{ input_field('password', '', 'password') }}
{{ textarea('comment') }}
如果是当前模板内定义的macros,那就不必导入了,直接使用特殊变量_self
{# index.html template #}
{% macro textarea(name, value, rows) %}
{% endmacro %}
{{ _self.textarea('comment') }}
{# index.html template #}
{% macro textarea(name, value, rows) %}
{% endmacro %}
{{ _self.textarea('comment') }}
那么你仍然可以导入_self到一个变量里,尽管这看起来很。。。没用。。
{# index.html template #}
{% macro textarea(name, value, rows) %}
{% endmacro %}
{% import _self as forms %}
{{ forms.textarea('comment') }}
{# index.html template #}
{% macro textarea(name, value, rows) %}
{% endmacro %}
{% import _self as forms %}
{{ forms.textarea('comment') }}
from标签
参见 import标签
摘自 jiaochangyun的专栏

tomodifyDatainAphPessess, startSessionstession_start (), 그런 다음 $ _sessionToset, modify, orremovevariables.

배열은 PHP 세션에 저장할 수 있습니다. 1. 세션을 시작하고 session_start ()를 사용하십시오. 2. 배열을 만들고 $ _session에 저장하십시오. 3. $ _session을 통해 배열을 검색하십시오. 4. 세션 데이터를 최적화하여 성능을 향상시킵니다.

PHP 세션 쓰레기 수집은 만료 된 세션 데이터를 정리하기위한 확률 메커니즘을 통해 트리거됩니다. 1) 구성 파일에서 트리거 확률 및 세션 수명주기를 설정합니다. 2) CRON 작업을 사용하여 고재 응용 프로그램을 최적화 할 수 있습니다. 3) 데이터 손실을 피하기 위해 쓰레기 수집 빈도 및 성능의 균형을 맞춰야합니다.

PHP의 사용자 세션 활동 추적은 세션 관리를 통해 구현됩니다. 1) Session_start ()를 사용하여 세션을 시작하십시오. 2) $ _session 배열을 통해 데이터를 저장하고 액세스하십시오. 3) 세션 _destroy ()를 호출하여 세션을 종료합니다. 세션 추적은 사용자 행동 분석, 보안 모니터링 및 성능 최적화에 사용됩니다.

데이터베이스를 사용하여 PHP 세션 데이터를 저장하면 성능 및 확장 성을 향상시킬 수 있습니다. 1) 세션 데이터를 저장하기 위해 MySQL 구성 : php.ini 또는 php 코드에서 세션 프로세서를 설정하십시오. 2) 사용자 정의 세션 프로세서 구현 : 데이터베이스와 상호 작용하기 위해 열린, 닫기, 읽기, 쓰기 및 기타 기능을 정의합니다. 3) 최적화 및 모범 사례 : 인덱싱, 캐싱, 데이터 압축 및 분산 스토리지를 사용하여 성능을 향상시킵니다.

phpsessionstrackuserdataacrossmultiplepagerequestsususingauniqueIdStoredInAcookie.here'showtomanagetheMeftically : 1) STARTASESSIONSTART_START () andSTAREDATAIN $ _SESSION.2) RegenerATERATESSESSIDIDAFTERLOGINWITHSESSION_RATERATERATES (True) TopreventSES

PHP에서 세션 데이터를 통한 반복은 다음 단계를 통해 달성 할 수 있습니다. 1. Session_start ()를 사용하여 세션을 시작하십시오. 2. $ _session 배열의 모든 키 값 쌍을 통해 Foreach 루프를 통과합니다. 3. 복잡한 데이터 구조를 처리 할 때 is_array () 또는 is_object () 함수를 사용하고 print_r ()를 사용하여 자세한 정보를 출력하십시오. 4. Traversal을 최적화 할 때 페이징을 사용하여 한 번에 많은 양의 데이터를 처리하지 않도록 할 수 있습니다. 이를 통해 실제 프로젝트에서 PHP 세션 데이터를보다 효율적으로 관리하고 사용하는 데 도움이됩니다.

이 세션은 서버 측 상태 관리 메커니즘을 통해 사용자 인증을 인식합니다. 1) 세션 생성 및 고유 ID의 세션 생성, 2) ID는 쿠키를 통해 전달됩니다. 3) ID를 통해 서버 저장 및 세션 데이터에 액세스합니다. 4) 사용자 인증 및 상태 관리가 실현되어 응용 프로그램 보안 및 사용자 경험이 향상됩니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Dreamweaver Mac版
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구
