【发布时间】:2019-07-24 18:10:28
【问题描述】:
我正在开发一个 Laravel 应用程序,我正在使用微前端(类似?)方法过渡到 React。我在 Laravel 中定义了一个辅助函数,它接收组件名称和 props 数组,并输出服务器端渲染的 React HTML。然后我在需要的地方调用我的视图中的这个函数。
我的应用程序中的每个页面都定义了一些变量,这些变量可能会影响这些 React 组件以及 Blade 模板的渲染。所以我在视图中定义了变量,并通过一个全局的window 变量将它们发送到 JavaScript 区域。但我在 SSR 助手中也需要这些变量。
现在我对如何做到这一点有两个想法:
- 在每次调用我的辅助函数时将变量作为道具传递。我想避免这种情况,因为变量在整个请求生命周期以及所有 @include 和 @extends 中都不会改变
- 在渲染视图之前使用
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