欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

How to use consts in Laravel blade templates? 模板 常量 const

Assume I would like to port a plain PHP app to Laravel. There is Settings class

class Settings
{
    const SID = "500000";
    const SECRET = "abscdefg";
}

// Clean access to constant
Settings::SID

Laravel suggests to use configs for such constants (am I right?)

[
    'SID' => '500000',
    'SECRET' = 'abscdefg'
]

The problem is that now instead of having identifiers (Settings::SID) I get magic strings everywhere (Config::get('SID'), or similar notation). What's the point? What benefits such strings create?

Now, In blade templates I still could use

// Auto completion works, while for facades it doesn't
{{ \App\Http\Settings\Settings::SID }}

instead of dealing with Config::get('SID'), however such long notation would quickly kill readability. I guess in blade template I could use

<?php
use \App\Http\Settings\Settings as Settings
?>
// Good enough but no auto-complete in PHPStorm
{{ Settings::SID }}

however using "use" in blade templates doesn't look right to me.

So what's the right way of handling [class] constants in Laravel blade templates?


来自  https://laracasts.com/discuss/channels/laravel/how-to-use-consts-in-laravel-blade-templates?page=1


laravel access to model constant in blade

Need access model constant in blade not with full path

class PaymentMethod extends Model {

const PAYPAL_ACCOUNT      = 'paypal_account';
const CREDIT_CARD         = 'credit_card';

and in blade

        {{ App\Classes\Models\PaymentMethod::CREDIT_CARD }}

work

but

        {{ PaymentMethod::CREDIT_CARD }}

throws Class 'PaymentMethod' not found

You may use aliases:

in your config\app.php under aliases section :

aliases => [
     ....
    'PaymentMethod' => App\Classes\Models\PaymentMethod::class
]

then use it in your balde file

{{ PaymentMethod::CREDIT_CARD }}

    来自  https://stackoverflow.com/questions/47270905/laravel-access-to-model-constant-in-blade


    普通分类: