定制 becklyn/javascript-context 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

becklyn/javascript-context

Composer 安装命令:

composer require becklyn/javascript-context

包简介

A way to send data from PHP to JavaScript.

README 文档

README

A simple library to send data from PHP to JavaScript.

Usage

Fetch the JavaScriptContext service:

use Becklyn\JavaScriptContext\Context\JavaScriptContext;


function doSomething (JavaScriptContext $context)
{
    $context
        ->set("some-data", 123)
        ->set("locale", "de");
}

Afterwards embed it in your twig template:

{{- javascript_context() -}}

The container will have the _javascript-context _data-container classes and the ID _javascript-context. To modify the ID, pass the new ID to the function:

{{- javascript_context(null, "some_other_id") -}}

Fetching the Data

To fetch the data from the script container, just JSON-parse it, after removing the HTML escaping, for example:

let data = JSON.parse(
   (document.getElementById("_javascript-context").textContent || "")
       .replace(/&lt;/g, "<")
       .replace(/&gt;/g, ">")
       .replace(/&amp;/g, "&")
);

In the JSON output, only the following chars are HTML escaped: <, > and &.

Context Providers

If some data has to always be passed to the template, then it is convenient to just register a context provider.

use Becklyn\JavaScriptContext\Context\JavaScriptContext;
use Becklyn\JavaScriptContext\Provider\ContextProviderInterface;

class MyProvider implements ContextProviderInterface
{
    public function provideJavaScriptContext (JavaScriptContext $context, ?string $domain) : void
    {
        $context->set("some", "value");
    }
}

Each provider receives the context to modify, as well as optionally a domain. This is just a string key with which the providers can decide whether they want to attach data or not.

For example to separate the context into app and backend you can just register all providers and then in your template include it like this:

{# in your frontend #}
{{- javascript_context("app") -}}


{# and in the backend do #}
{{- javascript_context("backend") -}

You must add the tag javascript_context.provider to your service. If you use autoconfiguration, the tag is added automatically.

统计信息

  • 总下载量: 876
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2019-06-12

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固