Symfony中不使用资产管理获取原始文件名公开文件的方法
Got it, let's break this down clearly. If you want to bypass Symfony's asset management (the {% javascripts %} tags that generate hashed filenames) and load your JS, CSS, images, etc., using their original filenames directly, here's exactly what you need to do:
1. Use the asset() function directly for bundle resources
If your static files are stored inside a bundle (like AppBundle/Resources/public/js/script.js), first make sure you've published the bundle's public assets to your project's web-accessible directory. Run this command in your terminal:
# For Symfony 3 and below php bin/console assets:install web --symlink # For Symfony 4+ (uses public/ instead of web/) php bin/console assets:install public --symlink
The --symlink flag creates a symbolic link instead of copying files, which is great for development since you don't have to re-run the command every time you edit a file.
Once that's done, you can reference the file in Twig using the asset() function with the correct path. For your example JS file:
<script src="{{ asset('bundles/app/js/script.js') }}"></script>
The path bundles/app/ maps directly to your AppBundle/Resources/public/ directory, so just mirror the subfolder structure (like js/, css/, images/) you have inside public/.
2. Directly reference files in the public/ directory (Symfony 4+)
If you're using Symfony 4 or later, a simpler approach is to place your static files directly in the project's root public/ folder (e.g., public/js/script.js, public/css/style.css). Then you can reference them with a shorter path:
<!-- JS file --> <script src="{{ asset('js/script.js') }}"></script> <!-- CSS file --> <link rel="stylesheet" href="{{ asset('css/style.css') }}"> <!-- Image --> <img src="{{ asset('images/logo.png') }}" alt="Site Logo">
This method skips bundle asset publishing entirely, making it more straightforward for modern Symfony projects.
Important Notes
- When you skip Symfony's asset management, you lose features like automatic file merging, minification, and cache-busting via hashed filenames. For production environments, you'll need to handle these optimizations manually (e.g., using tools like Gulp or Webpack) or consider using Symfony's Webpack Encore if you want to keep those benefits but still control filenames.
- Always ensure your files are in a web-accessible directory (either
public/or the publishedbundles/folder) so the browser can load them.
内容的提问来源于stack exchange,提问作者Bhavin Thummar

