twig 循环并创建阵列树枝

循环并创建阵列树枝

array.twig
{% set ct_arr = [] %}

{% for ct in app.config.get('contenttypes') if not ct.viewless|default(false) %}
    {% set ct_arr = ct_arr|merge([ct.slug]) %}
{% endfor %}

twig 工艺登录/登记表

工艺登录/登记表

log-in-include.twig
{% set notice = craft.session.getFlash('notice') %}
{% set error = craft.session.getFlash('error') %}

{% if error == "Couldn’t save user." %}
    {% set error = "We were unable to create your account. The most likely cause of this is that your email address is already being used for an account. If you need to resset your password, please <a href='/account/iforgot'>click here</a>." %}
{% endif %}

<div class="{% if loginExcludeMod is not defined %}mod mod--centered mod--max-900 u--centered{% endif %}{% if loginExcludeVerticalSpacing is not defined %} vertical-spacing-more{% endif %}">

    <div class="log-in-form log-in-form--double">

        {% if error %}
            <div class="block-note">
                <div class="block-note__title">
                    Error
                </div>
                <p>{{ error|smartypants }}</p>
            </div>
        {% endif %}

        {% if notice %}
            {% if notice == 'User registered.' %}
                <div class="block-note">
                    <div class="block-note__title">
                        Almost there!
                    </div>
                    <p>Your registration has been submitted successfully. Check your email to verify your account and complete your registration.</p>
                </div>
            {% else %}
                <div class="block-note">
                    <div class="block-note__title">
                        Notice
                    </div>
                    <p>{{ notice|smartypants }}</p>
                </div>
            {% endif %}
        {% endif %}

        {% if includeLoginH1 is not defined or (includeLoginH1 is defined and includeLoginH1 != false) %}
            {% if customLoginHeadingLevel is defined and customLoginHeadingLevel %}
                {% set headingLevel = customLoginHeadingLevel %}
            {% else %}
                {% set headingLevel = 1 %}
            {% endif %}
            <h{{ headingLevel }} class="heading heading--level-{{ headingLevel }} log-in-form__heading">
                {% if customLoginH1 is defined and customLoginH1 %}
                    {{ customLoginH1|smartypants }}
                {% else %}
                    Log In or Register
                {% endif %}
            </h{{ headingLevel }}>
        {% endif %}

        <div class="log-in-form__container">

            {# Log In #}
            <div class="log-in-form__left u--left">
                <h2 class="heading heading--level-3">Log In</h2>
                <form
                    class="log-in-form__form"
                    method="post"
                    accept-charset="UTF-8"
                >
                    {{ getCsrfInput() }}
                    <input type="hidden" name="action" value="users/login">

                    {% if loginRedirect is defined %}
                        <input type="hidden" name="redirect" value="{{ loginRedirect }}">
                    {% endif %}

                    {% if errorMessage is defined %}
                        <p>{{ errorMessage }}</p>
                    {% endif %}

                    <div class="log-in-form__input-container">
                        <label
                            for="loginName"
                            class="label log-in-form__label"
                        >
                            Email Address
                        </label>
                        <input
                            class="input log-in-form__input"
                            id="loginName"
                            type="email"
                            name="loginName"
                            value="{{ craft.session.rememberedUsername }}"
                        >
                    </div>

                    <div class="log-in-form__input-container">
                        <label
                            for="password"
                            class="label log-in-form__label"
                        >
                            Password
                        </label>
                        <input
                            class="input log-in-form__input"
                            id="password"
                            type="password"
                            name="password"
                        >
                    </div>

                    <div class="log-in-form__button-container">
                        <input class="button log-in-form__button" type="submit" value="Log In">
                        <p><a class="log-in-form__text-button" href="/account/iforgot">Forget your password?</a></p>
                    </div>
                </form>
            </div>

            {# Register #}
            <div class="log-in-form__right u--left">
                <h2 class="heading heading--level-3">Register</h2>
                <form
                    class="log-in-form__form"
                    method="post"
                    accept-charset="UTF-8"
                >
                    {{ getCsrfInput() }}
                    <input type="hidden" name="action" value="users/saveUser">
                    <input type="hidden" name="redirect" value="/account">
                    <input type="hidden" name="sendVerificationEmail" value="1">

                    {% macro errorList(errors) %}
                        {% if errors %}
                            <ul class="log-in-form__input-errors">
                                {% for error in errors %}
                                    <li class="log-in-form__input-error">
                                        {{ error }}
                                    </li>
                                {% endfor %}
                            </ul>
                        {% endif %}
                    {% endmacro %}

                    {% from _self import errorList %}

                    <div class="log-in-form__input-container">
                        <label
                            for="email"
                            class="label log-in-form__label"
                        >
                            Email Address
                        </label>
                        <input
                            class="input log-in-form__input{% if account is defined and account.getErrors('email')|length > 0 %} log-in-form__input--has-error{% endif %}"
                            id="email"
                            type="email"
                            name="email"
                            {% if account is defined %}
                            value="{{ account.email }}"
                            {% endif %}
                        >
                        {% if account is defined %}
                            {{ errorList(account.getErrors('email')) }}
                        {% endif %}
                    </div>

                    <div class="log-in-form__input-container">
                        <label
                            for="password"
                            class="label log-in-form__label"
                        >
                            Password
                        </label>
                        <input
                            class="input log-in-form__input{% if account is defined and account.getErrors('password')|length > 0 %} log-in-form__input--has-error{% endif %}"
                            id="password"
                            type="password"
                            name="password"
                        >
                        {% if account is defined %}
                            {{ errorList(account.getErrors('password')) }}
                        {% endif %}
                    </div>

                    <div class="log-in-form__button-container">
                        <input class="button log-in-form__button" type="submit" value="Register">
                    </div>
                </form>
            </div>

        </div>

    </div>

</div>

twig singleton.twig

singleton.twig
{% if not isallowed('contenttype:' ~ slug ~ ':create') and isallowed('contenttype:' ~ slug) and records|length == 1 and contenttype.show_in_menu == "true" %}

{% if not isallowed('contenttype:' ~ slug ~ ':create') and isallowed('contenttype:' ~ slug) and and contenttype.singleton == "true" %}

twig 来自http://craftcms.stackexchange.com/questions/10808/list-categories-and-their-associated-entries

来自http://craftcms.stackexchange.com/questions/10808/list-categories-and-their-associated-entries

list-categories-and-their-associated-entries.twig
<ul>
    {% for category in craft.categories.group('categoryGroupHandle') %}
    <li>
        {{ category.title }}
        {% for entry in craft.entries.section('sectionHandle').relatedTo(category) %}
            {% if loop.first %}<ul>{% endif %}
                <li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
            {% if loop.last %}</ul>{% endif %}
        {% endfor %}
        </ul>
    </li>
    {% endfor %}
</ul>

twig 来自http://craftcms.stackexchange.com/questions/9207/output-matrix-field-data

来自http://craftcms.stackexchange.com/questions/9207/output-matrix-field-data

output-matrix-fields.twig
{% for block in entry.myMatrixFieldHandle if block.type == "employment" %}
    <select>
        {% for option in block.myDropDownFieldHandle.options %}        
            <option value="{{ option.value }}">{{ option.label }}</option>
        {% endfor %}
    </select>
{% endfor %}

twig 来自http://craftcms.stackexchange.com/questions/749/how-do-i-adjust-the-page-title-for-different-section-and-entry-pages

来自http://craftcms.stackexchange.com/questions/749/how-do-i-adjust-the-page-title-for-different-section-and-entry-pages

page-title.twig
{% set title = entry.title %}

twig 来自http://craftcms.stackexchange.com/questions/824/test-for-empty-field

来自http://craftcms.stackexchange.com/questions/824/test-for-empty-field

test-for-empty.twig
{% if article.articleImage|length %}

twig 优化CSS字体加载

优化CSS字体加载

css-font-load.twig
		<link rel="stylesheet" href="/themes/transformer/css/fonts.css" type="text/css" media="none" onload="if(media!='all')media='all'">
		{if isset($css_files)}
			{foreach from=$css_files key=css_uri item=media}
				{if strpos($css_uri, "googleapis") !== false}
					<link rel="stylesheet" href="{$css_uri|escape:'html':'UTF-8'}" type="text/css" media="none" onload="if(media!='{$media|escape:'html':'UTF-8'}')media='{$media|escape:'html':'UTF-8'}'" />
					<noscript><link rel="stylesheet" href="{$css_uri|escape:'html':'UTF-8'}"></noscript>
				{else}
					<link rel="stylesheet" href="{$css_uri|escape:'html':'UTF-8'}" type="text/css" media="{$media|escape:'html':'UTF-8'}" />
				{/if}
			{/foreach}
		{/if}

twig 在drupal 8(bootstrap)主题中的twig循环中设置斑马风格(奇数/偶数)类

在drupal 8(bootstrap)主题中的twig循环中设置斑马风格(奇数/偶数)类

zebra.html.twig
<div{{ attributes.addClass('container') }}>
  {% for item in items %}
    {# NB! notation: loop.index is 1 start, loop.index0 is zero start #}
    <div class="row {{ loop.index0 is odd ? 'zebra-odd' : 'zebra-even' }}">
      <div{{ item.attributes }}>{{ item.content }}</div>
    </div>
  {% endfor %}
</div>

twig Twig扩展如何<br/> twig扩展示例(过滤器:数组排序)

Twig扩展如何<br/> twig扩展示例(过滤器:数组排序)

TwigSortExtensions.php
<?php

namespace RG\Dashboard\Extension;

use Patchwork\Utf8;
use Symfony\Component\DependencyInjection\ContainerInterface;
use /** @noinspection PhpUndefinedClassInspection */ Twig_Extension;


/**
 * Twig Extension filter : sort an array with differents strategies
 *
 * USORT : alphabetical order on a choosen field
 *  fill the parameters array with fields 'method' and possibly 'usortColName'
 *  Use example : {% ..... arrayName|rg_sort({'method':'usort', 'usortColName':'name'}) %}
 *
 * Other sorting methods
 *  fill the parameters array fields 'method' and possibly 'sortFlag' (see http://php.net/manual/fr/function.sort.php)
 *      Use example : {% arrayName|rg_sort({'method':'arsort', 'sortFlag':constant('SORT_REGULAR')}) %}
 * to deal with special chars (È, ...)
 */

// todo: params  en lc
// todo: gérer le flag SORT_FLAG_CASE et les OR ?

/** @noinspection PhpUndefinedClassInspection */
class TwigSortExtensions extends Twig_Extension
{
    protected $allowedMethods;
    protected $defaultMethod;
    protected $defaultSortflag;
    protected $allowedSortFlags;
    protected $container;
    protected $logger;
    protected $usortColName;

    public function __construct()
    {
        $this->allowedMethods = ['asort', 'arsort', 'krsort', 'natcasesort', 'narsort', 'rsort', 'sort', 'usort'];
        $this->defaultMethod = "asort" ;

        $this->allowedSortFlags = [SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_LOCALE_STRING, SORT_NATURAL];
        $this->defaultSortflag = SORT_REGULAR;

        $this->usortColName = null;
    }


    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
        $this->logger = $container->get('logger');
    }

    /**
     * Returns the name of the extension.
     * @return string The extension name
     */
    public function getName()
    {
        return 'Twig Sort Extensions';
    }

    /**
     * filter name
     * @return array
     */
    public function getFilters()
    {
        return array(
            'rg_sort' => new \Twig_Filter_Method($this, 'twigSort')
        );
    }

    /**
     * sorting method
     * @param $arrayToSort
     * @param $parameters: see class comments for détails
     * @return mixed: sorted array
     */
    public function twigSort($arrayToSort, $parameters=null)
    {
        $method = $this->defaultMethod;
        $sortFlag = $this->defaultSortflag;

        if ($parameters != null) {
            if (isset($parameters["method"]))
                $method = $parameters["method"];
            if (isset($parameters["sortFlag"]));
                $sortFlag = $parameters["sortFlag"];
        }

        if (! in_array($method, $this->allowedMethods))
            $method = $this->defaultMethod;
        if (! in_array($sortFlag, $this->allowedSortFlags))
            $sortFlag = $this->defaultSortflag;

        if ($method == "usort") {
            if ( (isset($parameters["usortColName"])) && (array_key_exists($parameters["usortColName"], reset($arrayToSort))) ) {
                $this->usortColName = $parameters["usortColName"];
            }

            $method($arrayToSort, [$this, "usort"]);
        }
        else {
            $method($arrayToSort, $sortFlag);
        }
        return $arrayToSort;
    }

    /**
     * usort method
     * @param $a
     * @param $b
     * @return int
     */
    protected function usort($a, $b)
    {
        $firstValue = ($this->usortColName != null) ? ($a[$this->usortColName]) : ($a);
        $secondValue = ($this->usortColName != null) ? ($b[$this->usortColName]) : ($b);

        $aConv = Utf8::toAscii($firstValue);
        $bConv = Utf8::toAscii($secondValue);

        return strcasecmp($aConv, $bConv);
    }


}
services.yml
.
.
.

    exemple_extensions:
        class: ....\Extension\TwigSortExtensions
        tags:
            -  { name: twig.extension }
in_a_twig.twig
    {% for name, service in services|rg_sort %}
    {% for name, service in services|rg_sort({'method':'arsort', 'sortFlag':constant('SORT_REGULAR')}) %}
    {% for name, service in services|rg_sort({'method':'usort', 'usortColName':'name'}) %}