You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Laravel分页器对Google Fonts返回的JSON数据分页?

解决Laravel中Google Fonts API数据的分页问题

首先看你现有代码里的小问题:你把集合存在了$r变量里,但传给视图的是result,这会导致视图拿不到数据。另外,用file_get_contents虽然能工作,但Laravel自带的Http客户端更优雅,还能处理错误情况。

接下来是分页的实现步骤:

第一步:修正并完善控制器代码

Google Fonts API返回的JSON结构里,字体数据是在items字段下的数组,我们需要提取这个数组,再用Laravel的LengthAwarePaginator来手动创建分页(因为API本身不支持分页参数)。

use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Http;

public function googleFonts(Request $request)
{
    // 调用Google Fonts API
    $apiKey = '你的API密钥';
    $response = Http::get("https://www.googleapis.com/webfonts/v1/webfonts?key={$apiKey}");
    
    // 检查请求是否成功
    if (!$response->successful()) {
        abort(500, 'Failed to fetch Google Fonts data');
    }

    $fontData = $response->json();
    $fonts = collect($fontData['items']); // 提取字体数组转为集合

    // 分页处理
    $perPage = 10; // 自定义每页显示的字体数量
    $currentPage = $request->input('page', 1);
    $paginatedFonts = new LengthAwarePaginator(
        $fonts->slice(($currentPage - 1) * $perPage, $perPage)->values(),
        $fonts->count(),
        $perPage,
        $currentPage,
        ['path' => $request->url(), 'query' => $request->query()]
    );

    return view('googleFonts', compact('paginatedFonts'));
}

第二步:在视图中渲染分页和字体数据

在googleFonts.blade.php里,你可以这样遍历字体并添加分页链接:

<!-- 遍历分页后的字体数据 -->
<div class="font-list">
    @foreach($paginatedFonts as $font)
        <div class="font-item">
            <h3>{{ $font['family'] }}</h3>
            <p>Available weights: {{ implode(', ', $font['variants']) }}</p>
            <!-- 可以在这里添加字体预览效果 -->
            <span style="font-family: '{{ $font['family'] }}'; font-size: 1.2rem;">The quick brown fox jumps over the lazy dog</span>
        </div>
    @endforeach
</div>

<!-- 渲染Laravel自带的分页链接 -->
<div class="pagination mt-4">
    {{ $paginatedFonts->links() }}
</div>

第三步:性能优化建议

每次请求都调用Google Fonts API会拖慢页面速度,建议用Laravel的缓存系统把数据存起来,比如缓存24小时:

// 替换控制器里的API调用部分为缓存逻辑
use Illuminate\Support\Facades\Cache;

$fonts = Cache::remember('google_fonts', 86400, function () use ($apiKey) {
    $response = Http::get("https://www.googleapis.com/webfonts/v1/webfonts?key={$apiKey}");
    return collect($response->json()['items']);
});

这样只有第一次请求会调用外部API,后续请求直接读取缓存,性能会提升很多。


内容的提问来源于stack exchange,提问作者kristi tanellari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:34:06