搜尋
首頁php框架Laravel關於laravel自訂範本指令-tojs

下面由Laravel教學專欄為大家介紹laravel自訂範本指令-tojs  ,希望對需要的朋友有幫助!

Blade 允許你自訂指令,你可以使用 directive 方法註冊指令。當 Blade 編譯器遇到該指令時,它將會帶著參數呼叫提供的回呼函數。 blade範本可以透過directive方法來自訂範本指定,

tojs指令主要用於PHP自訂一些資料轉換為js物件方便js呼叫

1.建立ToJsServiceProvider

<?php namespace App\Providers;

use App\Helpers\ToJs\ToJs;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class ToJsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('tojs', function () {
            return new ToJs();
        });

        /*
        * The block of code inside this directive indicates
        * the chosen javascript variables.
        */
        Blade::directive('tojs', function () {
            return '<script> window.Laravel = &#39; . json_encode(app(&#39;tojs&#39;)->get()) . &#39;</script>';
        });
    }
}

2. ToJs方法主要是對陣列的一些操作

<?php namespace App\Helpers\ToJs;

use Illuminate\Support\Arr;

class ToJs
{
    protected $data = [];

    public function put(array $data)
    {
        foreach ($data as $key => $value) {
            $this->data[$key] = value($value);
        }

        return $this;
    }

    public function get($key = null, $default = null)
    {
        if (!$key) return $this->data;

        return Arr::get($this->data, $key, $default);
    }

    public function forget($keys)
    {
        Arr::forget($this->data, $keys);

        return $this;
    }
}

3.宣告facade

namespace App\Helpers\ToJs\Facades;

use Illuminate\Support\Facades\Facade;


class ToJsFacade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'tojs';
    }
}

4.在config陣列中加入serviceProvider

providers 新增
\App\Providers\ToJsServiceProvider::class

aliases 加入
'ToJs' => \App\Helpers\ToJs\Facades\ToJsFacade::class,

5.為了方便呼叫可以在寫一個helper方法

if (!function_exists('to_js')) {
    /**
     * Access the javascript helper.
     */
    function to_js($key = null, $default = null)
    {
        if (is_null($key)) {
            return app('tojs');
        }

        if (is_array($key)) {
            return app('tojs')->put($key);
        }

        return app('tojs')->get($key, $default);
    }
}

在PHP程式碼需要的地方呼叫to_js(['username'=>'test'] );

blade模板直接透過@tojs 就可以在頁面渲染出
<script> window.Laravel = {"username":"test "}</script>

#

以上是關於laravel自訂範本指令-tojs的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:csdn。如有侵權,請聯絡admin@php.cn刪除
包容的幻想:解決偏遠工作中的孤立和孤獨感包容的幻想:解決偏遠工作中的孤立和孤獨感Apr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel用於全堆棧開發:綜合指南Laravel用於全堆棧開發:綜合指南Apr 25, 2025 am 12:27 AM

laravelispularfullull-stackDevelopmentBecapeitOffersAsAseAseAseAseBlendOfbackendEdpoperandPowerandForterFlexibility.1)ITSbackEndCapaPabilities,sightifyDatabaseInteractions.2)thebladeTemplatingEngingEngineAllolowsLows

視頻會議攤牌:為遠程會議選擇正確的平台視頻會議攤牌:為遠程會議選擇正確的平台Apr 25, 2025 am 12:26 AM

選擇視頻會議平台的關鍵因素包括用戶界面、安全性和功能。 1)用戶界面應直觀,如Zoom。 2)安全性需重視,MicrosoftTeams提供端到端加密。 3)功能需匹配需求,GoogleMeet適合簡短會議,CiscoWebex提供高級協作工具。

哪些數據庫版本與最新的Laravel兼容?哪些數據庫版本與最新的Laravel兼容?Apr 25, 2025 am 12:25 AM

最新版本的Laravel10與MySQL5.7及以上、PostgreSQL9.6及以上、SQLite3.8.8及以上、SQLServer2017及以上兼容。這些版本選擇是因為它們支持Laravel的ORM功能,如MySQL5.7的JSON數據類型,提升了查詢和存儲效率。

將Laravel用作全棧框架的好處將Laravel用作全棧框架的好處Apr 25, 2025 am 12:24 AM

Laravelisanexcellentchoiceforfull-stackdevelopmentduetoitsrobustfeaturesandeaseofuse.1)ItsimplifiescomplextaskswithitsmodernPHPsyntaxandtoolslikeBladeforfront-endandEloquentORMforback-end.2)Laravel'secosystem,includingLaravelMixandArtisan,enhancespro

Laravel的最新版本是什麼?Laravel的最新版本是什麼?Apr 24, 2025 pm 05:17 PM

Laravel10,releasedonFebruary7,2023,isthelatestversion.Itfeatures:1)Improvederrorhandlingwithanewreportmethodintheexceptionhandler,2)EnhancedsupportforPHP8.1featureslikeenums,and3)AnewLaravel\Promptspackageforinteractivecommand-lineprompts.

最新的Laravel版本如何簡化開發?最新的Laravel版本如何簡化開發?Apr 24, 2025 pm 05:01 PM

thelatestlaravelververversionenhancesdevelopmentwith:1)簡化的inimpliticmodelbinding,2)增強EnhancedeloquentcapabibilitionswithNewqueryMethods和3)改善了supportorfortormodernphpfortornphpforternphpfeatureserslikenamedargenamedArgonedArgonsemandArgoctess,makecodingMoreftermeforefterMealiteFficeAndEnjoyaigaigaigaigaigaiganigaborabilyaboipaigyAndenjoyaigobyabory。

在哪裡可以找到最新的Laravel版本的發行說明?在哪裡可以找到最新的Laravel版本的發行說明?Apr 24, 2025 pm 04:53 PM

你可以在laravel.com/docs找到最新Laravel版本的發布說明。 1)發布說明提供了新功能、錯誤修復和改進的詳細信息。 2)它們包含示例和解釋,幫助理解新功能的應用。 3)注意新功能的潛在復雜性和向後兼容性問題。 4)定期審查發布說明可以保持更新並激發創新。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能