Flask-CookieCutter中asset_url_for()返回None的图片访问问题
I’ve worked with this exact Flask-CookieCutter + Flask-Webpack setup before, so let’s break down why your images aren’t loading and fix this step by step:
1. Fix the File-Loader Parameter Syntax
Looking at your Webpack config, the file-loader rule uses an HTML entity (&) instead of a plain & to separate parameters. This breaks how Webpack parses the loader options, so it can’t correctly map your images to the manifest file.
Update this rule in your module.rules section:
{ test: /\.(ttf|eot|svg|png|jpe?g|gif|ico)(\?.*)?$/i, // Replace & with a regular & to fix parameter parsing loader: `file-loader?context=${rootAssetPath}&name=[path][name].[hash].[ext]` },
2. Ensure Images Are Added to the Manifest
By default, the ManifestRevisionPlugin only tracks files referenced in your entry points (your JS/CSS files). If you’re referencing images directly in Flask templates (not importing them in JS/CSS), they won’t show up in the manifest—which is why asset_url_for returns None.
Update the ManifestRevisionPlugin configuration to explicitly scan your img directory:
new ManifestRevisionPlugin(path.join(__dirname, 'dsi_website', 'webpack', 'manifest.json'), { rootAssetPath, ignorePaths: ['/js', '/css'], // Add this pattern to include all image files in assets/img patterns: [ { pattern: 'img/**/*', path: rootAssetPath, } ] }),
3. Verify Template Usage
Make sure you’re using asset_url_for with the correct path relative to your assets directory. For an image located at assets/img/img_name.png, the correct template call is:
{{ asset_url_for('img/img_name.png') }}
After making these changes, restart your Webpack Dev Server and check the dsi_website/webpack/manifest.json file. You should see an entry for your image that looks like this:
"img/img_name.png": "static/build/img/img_name.[hash].png"
Why url_for('static', ...) Doesn’t Work
In development mode, Webpack Dev Server serves assets from memory—not from Flask’s static directory. The actual image files aren’t present in dsi_website/static/build until you run a production build, so Flask can’t locate them with the standard url_for method. asset_url_for is purpose-built to pull the correct URL from the Webpack manifest, which points to the Webpack Dev Server in development.
Give these tweaks a try, and your images should load correctly in the development environment!
内容的提问来源于stack exchange,提问作者Craicerjack

