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

使用Jinja与GitHub Actions构建静态网站:页面生成后无法部署

从GitLab Pages迁移到GitHub Pages后,Jinja生成的index.html文件无法找到

我正在把一个基于Python/Jinja的静态网站模板从GitLab Pages迁移到GitHub Pages,使用GitHub Actions构建。脚本运行无报错,但生成的index.html文件无处可寻。已确认GitHub Actions读写权限开启,仍无法解决问题。

原GitLab CI配置

image: python:3.6-alpine

pages:
  stage: deploy
  before_script:
  - python -m pip install -r requirements.txt
  script:
  - cd public/
  - python render.py
  - cd ..
  artifacts:
    paths:
    - public/

迁移后的GitHub Actions配置

name: Build and Deploy

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest  # use the latest version of ubuntu

    steps:
    - name: Checkout code
      uses: actions/checkout@v3 #v3 to ensure that everything is run on node16

    - name: Set up Python
      uses: actions/setup-python@v3 #v3, node12 will be deprecated soon
      with:
        python-version: 3.9  #just upgrading from the alpine 3.6 version

    - name: Install dependencies
      run: |
        python -m pip install -r requirements.txt #install the requirements

    - name: Build and Deploy
      run: |
        cd public/
        python render.py
        cd ..

    - name: Upload artifacts
      uses: actions/upload-artifact@v3
      with:
        name: public
        path: public/

public目录下的render.py代码

import json
import yaml
from jinja2 import Environment, FileSystemLoader, DebugUndefined
from jinja2_markdown import MarkdownExtension
from pathlib import Path
import datetime
from glob import glob  # Add this line for importing glob
from tqdm import tqdm

# Create an empty dictionary to store template variables to be passed
data = dict()

# Add today's date, properly formatted, to the data dict to display at the bottom
# of the page
data['today'] = datetime.date.today().strftime('%Y-%m-%d')

# Load assets that can be used by templates. Assets are yaml files with data
for pathname in tqdm(glob('assets/*.y*ml'), desc='Loading assets'):
    path = Path(pathname)
    fname = path.stem
    with path.open('r') as f:
        assetdata = yaml.safe_load(f)
    if type(assetdata) is not dict:
        assetdata = {fname: assetdata}
    data.update(assetdata)

# Scan sections in the sections directory; there will be a section header for
# each one of these
data['sections'] = []
sectionfiles = glob('sections/*.html')
try:
    order = yaml.safe_load(Path('sections/order.yaml').open('r'))
    comparator = lambda key: (order + [Path(key).stem]).index(Path(key).stem)
except FileNotFoundError:
    comparator = lambda key: key
for sectionfile in tqdm(sorted(sectionfiles, key=comparator), 
                        desc='Processing sections'):
    sectionfile = Path(sectionfile)
    fname = sectionfile.stem
    sectionenv = Environment(loader=FileSystemLoader('sections'), 
                             extensions=['jinja2_markdown.MarkdownExtension'],
                             undefined=DebugUndefined)
    sectiontempl = sectionenv.get_template(sectionfile.name)
    data['sections'] += [dict(name=fname, content=sectiontempl.render(**data))]

# Create a Jinja2 environment instance
jinja_env = Environment(loader=FileSystemLoader('templates'), 
                        extensions=['jinja2_markdown.MarkdownExtension'],
                        undefined=DebugUndefined)
# Get template
template = jinja_env.get_template('landing.html')

# Render template and output it to index.html, the default page to show
output_path = Path('output')  #change path as needed
output_path.mkdir(exist_ok=True)

output_file_path = output_path.joinpath('index.html')
with output_file_path.open('w') as out:
    out.write(template.render(**data))

print(f"index.html saved at: {output_file_path}")

问题原因及解决方法

  1. 输出路径不匹配GitHub Pages要求
    GitHub Pages默认从public根目录读取静态文件,但当前render.py将index.html生成到了public/output/目录下,且GitHub Actions仅上传public/目录作为 artifact,并未将构建产物部署到GitHub Pages或推回仓库。

  2. 调整输出路径到public根目录
    修改render.py中的输出逻辑,直接将index.html生成到public根目录:

    # 替换原输出路径相关代码
    output_file_path = Path('index.html')
    with output_file_path.open('w') as out:
        out.write(template.render(**data))
    
  3. 完善GitHub Actions部署步骤
    当前配置仅上传了构建产物,未部署到GitHub Pages。添加部署步骤,使用官方工具完成部署:
    在GitHub Actions配置的Upload artifacts步骤后添加:

    - name: Deploy to GitHub Pages
      uses: peaceiris/actions-gh-pages@v3
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        publish_dir: ./public
    

    同时需在仓库设置中开启GitHub Pages,选择gh-pages分支作为源。

  4. 验证构建产物是否生成
    在Build and Deploy步骤中添加文件查看命令,确认index.html是否存在:

    - name: Build and Deploy
      run: |
        cd public/
        python render.py
        ls -la output/  # 查看output目录下的文件
        cd ..
    

    通过Actions日志可确认文件生成状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:27:50