如何使"global"变量在拉拉维尔助手和视图中可用?



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

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

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

  1. 在每次调用我的帮助程序函数时将变量作为 props 传递。我想避免这种情况,因为变量在整个请求生命周期和所有@includes和@extends中永远不会改变
  2. 在呈现视图之前config帮助程序设置值。这似乎有点不合时宜,因为我认为config应该与更多的"静态"值一起使用(适用于整个应用程序而不是特定页面),但我不太精通 Laravel-world,所以这实际上是可以接受的。

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

一些代码:

我的模板刀片.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

主/索引刀片.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助手.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).
*/
}

如果每个页面总是得到相同的值,那么你应该在你的配置中的某个地方设置一个数组,其中键是页面,值是收到的 props。顺便说一下,你会得到:

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

我很高兴看到人们使用微前端在像Laravel这样的非JavaScript框架中使用React来渲染服务器端渲染。

我建议你看看这篇文章 使用 Vue.js 和 Ara 框架在 Laravel 中进行通用渲染。Ara 框架也支持 React,我认为服务器端包含方法是克服 Blade 限制的最佳选择。

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

最新更新