Brand new to Craft here. I'm trying to port across my gulp workflow to Craft and basically everything has gone super smooth. Just one last obstacle due to my lack of knowledge of the Twig templating engine and some of the internal workings of Craft.
Basically, for production, I run gulp with a --production
flag. This appends a string of numbers and letters to the asset's file name (as well as removing source maps etc.), such as main-5449f384.css
, to help with caching. A list of the resulting asset filenames is stored in a JSON file at public/dist/assets.json
. The contents of the file is akin to:
{
"main.css": "main-5449f384.css",
"modernizr.js": "modernizr-45f0e1f4.js",
"jquery.js": "jquery-e735354d.js",
"main.js": "main-b7e504b0.js"
}
Separately, in my general.php
config file, I've set up environment variables so I can use local asset paths in local and dev environments and a CDN based path in production:
return array(
'*' => array(
'appId' => 'example',
'omitScriptNameInUrls' => true,
),
'example.com' => array(
'devMode' => false,
'assetUrl' => 'https://cdn.example.com/',
),
'craft' => array(
'devMode' => true,
'local' => true,
'assetUrl' => 'http://craft:8888/',
)
);
I had figured that to finalise the whole workflow, my head
section within craft/templates/_layout.html
would look something like (using a if statement to get the current environment):
Local
<script src="{{ craft.config.assetUrl }}dist/scripts/main.js"></script>
Live (pseudocode)
<script src="{{ craft.config.assetUrl }}dist/scripts/{{ assets.json.main.js }}"></script>
Is there a way to either set an environment variable based on the contents of the JSON file or to access to JSON file contents directly from within the template file? Or perhaps there's a much better way of doing this altogether (I'd quite like to keep the currently gulp workflow as is if possible)!