【问题标题】:How to make "global" variable available in Laravel helper and view?如何在 Laravel 助手和视图中使“全局”变量可用?
【发布时间】:2019-07-24 18:10:28
【问题描述】:

我正在开发一个 Laravel 应用程序,我正在使用微前端(类似?)方法过渡到 React。我在 Laravel 中定义了一个辅助函数,它接收组件名称和 props 数组,并输出服务器端渲染的 React HTML。然后我在需要的地方调用我的视图中的这个函数。

我的应用程序中的每个页面都定义了一些变量,这些变量可能会影响这些 React 组件以及 Blade 模板的渲染。所以我在视图中定义了变量,并通过一个全局的window 变量将它们发送到 JavaScript 区域。但我在 SSR 助手中也需要这些变量。

现在我对如何做到这一点有两个想法:

  1. 在每次调用我的辅助函数时将变量作为道具传递。我想避免这种情况,因为变量在整个请求生命周期以及所有 @include 和 @extends 中都不会改变
  2. 在渲染视图之前使用config 助手设置值。这似乎有点单调,因为我认为 config 应该与更多“静态”值一起使用(适用于整个应用程序而不是特定页面),但我不太精通 Laravel 世界,所以这实际上可能可以接受。

所以现在我更倾向于 2,但我想知道是否有更好的选择?

一些代码:

我的模板.blade.php

//these are the variables that I want to access in my helper
@extends('master.index', [
  "_PAGE_CONFIG" => [
    "page" => "blog",
    "header" => ["search" => true]
  ]
]);

@section('content')

@include('some-template.that-also-has.ssr-components-in-it')

{!! ssr('blog/Blog', ["posts" => $posts]) !!}

@endsection

master/index.blade.php

<body>

@if($_PAGE_CONFIG["header"])
<header>{!! ssr('header/Header') !!}</header>
@endif

@yield('content')

<script>
//here I pass my variables to (client) JS land
window._PAGE_CONFIG = @json($_PAGE_CONFIG);
</script>

</body>

我的-SSR-helper.php

function ssr($component, $props = []) {
  /*
  here I call a node server or script that handles the rendering for me,
  but I want to pass it $_PAGE_CONFIG, which will be different in each page.
  I could pass it in each ssr call in the template but this is what I want to avoid
  as this function might be called several times down the @include/@extend chain
  and $_PAGE_CONFIG never changes in any one page
  (but might be different for different pages).
  */
}

【问题讨论】:

    标签: reactjs laravel laravel-blade server-side-rendering


    【解决方案1】:

    如果每个页面总是获得相同的值,那么您应该在配置中的某处设置一个数组,其中键是页面,值是收到的道具。顺便说一句,你会得到:

    function ssr($component, $page, $props = []) {
      $pageProps = config('somewhere.'.$page);
    }
    

    【讨论】:

    • 我不需要为所有视图创建一个全局通用值,我需要从全局视图中创建一个值。
    • 我不习惯 SSR,能否请您发布一些代码示例以了解您的上下文?如果你构建你的 JS 文件,你可以使用 Laravel mix 来注入一些环境变量。
    • 在原始帖子中添加了一些最小示例
    • 好的,关于这些变量,它们是在同一页面上动态显示的,还是每次都有 1 个页面获取相同的值?
    • 每个页面每次都有相同的值,它们只是页面之间的不同
    【解决方案2】:

    我很高兴看到人们使用微前端在 Laravel 等非 JavaScript 框架中使用 React 进行服务器端渲染。

    我建议你看看这篇文章Universal Rendering in Laravel using Vue.js and Ara Framework。 Ara Framework 也支持 React,我认为服务器端包含方法是克服 Blade 限制的最佳选择。

    本文可以为您提供有关此方法如何工作的背景信息。 https://itnext.io/strangling-a-monolith-to-micro-frontends-decoupling-presentation-layer-18a33ddf591b

    【讨论】:

      猜你喜欢
      • 2011-03-02
      • 2011-08-31
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2019-08-05
      相关资源
      最近更新 更多