高级

高级

添加新的PHP函数

将您自己的PHP函数添加到Gantry主题是可以实现的,并且可以是一个非常简单的过程,这要感谢(Dependency Injection 依赖注入)。本指南将带您完成向站点添加自己的PHP函数所需的步骤。

在本例中,我们将添加移动检测,一个用于检测移动设备(包括平板)的开源PHP类,使您能够在您的站点上创建特定于设备的响应。

如果您从头开始开发自己的主题,那么这是完成此任务的一个很好的方法。这一过程预计不会成为现有主题用户长期使用的标准解决方案。重写主题。在现有主题上的php可能会在升级时引发问题。一个更干净、更直观的扩展PHP功能的过程在工作中,当它可用时,这个文档将被更新。

重写theme.php文件

包括includes/theme.php文件定义了主题,它还可以用来添加额外的PHP函数。

此时不可能重写theme.php,当功能可用时,您将能够在custom/include /目录下创建该文件的覆盖,以便在主题被更新的情况下进行更改并保存它们。

既然这是不可能的,你需要直接编辑主题。位于根目录下的theme.php,建议您创建一个文件副本,以防您需要恢复到原来的状态。

准备使用移动检测

要添加移动检测php函数,我们首先需要下载该库。您可以获取最新的Mobile_Detect.php的稳定版本。并将其放在 custom/includes/文件夹中。

您的主题文件夹现在应该是这样的:

+ g5_hydrogen
  + includes
    + theme.php
  + custom
    + includes
      - Mobile_Detect.php

现在,您已经准备好通过编辑主题将Mobile_Detect注入到gantry中theme.php文件并在文件底部添加以下简单的代码行:

// Require the Mobile Detect library
include_once dirname(__FILE__).'/../custom/includes/Mobile_Detect.php';

// Dependency Injection of Mobile Detect
$gantry['mobile_detect'] = new \Mobile_Detect();

这将使移动检测库可以通过访问twig文件gantry.mobile_detect。移动检测提供的任何方法现在都可以使用。

将该类放在一起使用

一旦您完成了注入的类,您将能够从任何主题的Twig文件中引用它。这包括主题的核心Twig文件,单个粒子等。

下面是一个调用移动检测的例子。

{%- if not gantry.mobile_detect.isMobile() -%}
    THIS DEVICE IS NOT A MOBILE
{%- endif -%}

实例研究

让我们创建一个简单新移动检测粒子,并将我们所学的所有内容合在一起。

第一步是为这个新粒子创建所需的YAML和Twig文件。您可以通过创建一个新文件夹来实现这一点custom/particles(如果没有的话),并添加两个新文件:mobile_detect.html.twig 和 mobile_detect.yaml.

+ g5_hydrogen
  + custom
    + particles
      - mobile_detect.html.twig
      - mobile_detect.yaml

为了这个实例,这个粒子将会是一个非常简单的粒子,这是我们将用于它的文件的内容:

mobile_detect.html.twig

{% extends '@nucleus/partials/particle.html.twig' %}

{% block particle %}
    <div>You are using Mobile Detect v<strong>{{ gantry.mobile_detect.getScriptVersion() }}</strong></div>
    <div>
        {% set device = (gantry.mobile_detect.isMobile() ? (gantry.mobile_detect.isTablet() ? 'tablet' : 'phone') : 'computer') %}
        Your device is a <strong>{{ device }}</strong>
    </div>
    <p>
        {% for name, match in gantry.mobile_detect.getProperties() %}
            {% set check = gantry.mobile_detect.version(name) %}
            {% if check != false %}
                <div>version(<strong>{{ name }}</strong>) => <strong>{{ check }}</strong></div>
            {% endif %}

        {% endfor %}
    </p>
    <div>
        {{ gantry.mobile_detect.is('chrome') }}
    </div>
    <div>Your User Agent is: <pre>{{ gantry.mobile_detect.getUserAgent() }}</pre></div>
{% endblock %}

mobile_detect.yaml

name: Mobile Detect
description: Example Particle
type: particle

在这一点上,Mobile Detect粒子将出现在Gantry 5管理器。您现在可以在布局管理器中任意位置拖放粒子,并在保存后将看到正在使用的移动检测。

刷新前端,你会看到这样的东西:

Gantry添加新的PHP函数

说点什么...
取消
你是一个访客 ( 注册 ? )
作为一个访客
加载评论... 注释将在之后刷新 00:00.

第一个发表评论

joomlass-logo31.png

Search


Notice: Only variables should be assigned by reference in /www/wwwroot/www.joomlass.com/plugins/system/sixecontactonline/tmpl/default.html.php on line 13