Using Assetic's Css Rewriter outside of Symfony - assetic

Let me start by saying I have absolutely no idea what I should be doing because the documentation and available information on Assetic is either limited or Symfony oriented.
Here is my folder structure.
Assetic
+ assets
+ css
+ example.css
+ docs
+ src
+ tests
+ vendor
+ index.php
+ styles.php
Now, I have the following test code. Basically I cloned a clean copy of Assetic and ran composer install. Then I create an index.php file which simply links to my styles.php file with HTMLs <link> tag.
Here is my styles.php
<?php
require 'vendor/autoload.php';
$assetPath = __DIR__.'/assets/css/example.css';
$assetBasePath = __DIR__.'/assets/css';
$asset = new Assetic\Asset\FileAsset($assetPath, array(), $assetBasePath, 'example.css');
header('Content-Type: text/css');
$asset->setTargetPath(__DIR__);
echo $asset->dump(new Assetic\Filter\CssRewriteFilter);
Here is my example.css stylesheet.
body {
background-image: url('../img/background.png');
}
When I load up the styles.php in my browser I get the following output.
url('../img/background.png');
That's the same as the actual CSS. If I use the CSS URI Rewriter from Mr. Clay I get the expected output.
url('/Assetic/assets/img/background.png');
So what am I doing wrong with Assetic? I have no idea what paths I should be passing in and to where.
Thanks.

Just a pretty hard time with it, but finally (after reading the doc. of webassets, python library on which assetic is based) I won over the lack of documentation.
Here you go
<?php
require 'vendor/autoload.php';
$assetPath = __DIR__.'/assets/css/example.css';
$asset = new Assetic\Asset\FileAsset($assetPath, array(new Assetic\Filter\CssRewriteFilter), dirname($assetPath), '/assets/css');
// I assume the 'assets' directory is at the root of your website
header('Content-Type: text/css');
$asset->setTargetPath('/path/to/dumped/asset');
// As above, it's the path to the generated asset from your http root
echo $asset->dump();
I'm not sure to be very clear, so ask if you didn't understand something.

Related

MYTHEME_preprocess_paragraph__PARAGRAPHTYPE not loading

I am slowly learning D8 while implementing my website, and decided to follow https://www.webwash.net/how-to-create-powerful-container-paragraphs-in-drupal-8/ to start my landing page.
Starting the hook_preprocess section, I assumed this would go in:
THEMES/MYBOOTSTRAPSUBTHEME/MYTHEMENAME.theme
<?php
/**
* #file
* Bootstrap sub-theme.
*
* Place your custom PHP code in this file.
*/
function MYSUBTHEMENAME_preprocess_paragraph__banner(&$variables) {
$paragraph = $variables['paragraph'];
if (!$paragraph->field_image->isEmpty()) {
$image = $paragraph->field_image->entity->url();
$variables['attributes']['style'][] = 'background-image: url("' . $image . '");';
$variables['attributes']['style'][] = 'background-size: cover;';
$variables['attributes']['style'][] = 'background-position: center center;';
}
}
I have cleared cache from the Configuration page with no luck. This is built localhost using MAMP (PHP 7.1.6) - if of any use.
I have double checked all the configurations that the tutorial shows and all the names are correct (banner, field_image). I just can't seem to find the issue!
Any suggestions?
If it is not a typo your themename is not MYBOOTSTRAPSUBTHEME, it is MYTHEMENAME as you said:
THEMES/MYBOOTSTRAPSUBTHEME/MYTHEMENAME.theme
Therefore the function should be called:
function MYTHEMENAME_preprocess_paragraph__banner(&$variables) {
// If devel module is enabled you may check if it is working
// by adding some debug output:
// dpm('debug');
}
Make sure to use lowercase letters for directory- file and function name. After implementing the function do not forget to rebuild cache. It's not necesary to have a twig template file paragraphs-banner.twig, it should work without that too.

Gulp-Inject Not Working

I have a simple Gulp build process setup for testing. I've read the documentation many times but I can't seem to get Gulp-inject to inject the scripts I want into an index.html file.
My Gulp file looks like this:
gulp.task('inject1', function() {
return gulp.src('app/index.html')
.pipe(inject(gulp.src('./app/scripts/app.js', {read : false}))) // Not necessary to read the files (will speed up things), we're only after their paths
.pipe(gulp.dest("dist"));
});
gulp.task('inject2', function() {
return gulp.src('app/scripts/**/*.js', {read : false}) // Not necessary to read the files (will speed up things), we're only after their paths
.pipe(inject("./app/index.html"))
.pipe(gulp.dest("./dist"));
});
This is part of my Index.html:
<!-- inject:js -->
<!-- endinject-->
Both of these are copied from the documentation on github.
When I run either of these tasks the console just says "Started 'inject' Finished 'Inject' '
In my ./dist folder it creates an Index.html file but no js files are injected.
I've tried typing in the src and inject properties many different way but no luck. Any idea what I'm doing wrong?
First of all you have a mistake in your endinject tag:
<!-- endinject-->
should be
<!-- endinject -->
This plugin has worked great for me and others in various settings, so the problem is probably in your configuration.
Because when you are using streaming, you cannot be sure which files you pipe along, always try to use a plugin to see exactly what files you are piping. I recommend using gulp-using. Try this to debug your setup:
var debug = require('gulp-debug');
gulp.task('inject2', function() {
return gulp.src('app/scripts/**/*.js', {read : false})
.pipe(debug())
.pipe(inject("./app/index.html"))
.pipe(gulp.dest("./dist"));
});
Also make sure you use the same method to verify that you match your html file as well.
Other than that - it's just trial and error until you understand piping to get just the right files with the correct path.
If gulp-inject isn't injecting any files, that means you didn't pipe them correctly, or your target inject was not correct. The plugin works, and works great for me.
If you need to see an example working gulp file, check out this this gulpfile.js gist
I had the same problem with the following code:
var injectSrc = gulp.src(['./public/css/*.css', '.public/js/*.js'], {read: false});
var injectOptions = {
ignorePath: '/public'
};
var options = {
bowerJson: require('./bower.json'),
directory: './public/lib',
ignorePath: '../../public'
}
gulp.task('inject', function() {
return gulp.src('./src/views/*.html')
.pipe(debug())
.pipe(wiredep(options))
.pipe(debug())
.pipe(inject(injectSrc, injectOptions))
.pipe(debug())
.pipe(gulp.dest('./src/views'));
});
My index.html had the following:
<!--bower:css-->
<!--endbower-->
<!--bower:js-->
<!--endbower-->
<!--inject:css-->
<!--endinject-->
<!--inject:js-->
<!--endinject-->
Click on this link to see what my file structure was.
The inject was creating the css files correctly but not the js files. Also the bower dependencies were working just fine.
Finally I caught the missing '/' in the array passed to gulp.src(). After fixing that to:
var injectSrc = gulp.src(['./public/css/*.css', './public/js/*.js'], {read: false});
it works correctly.

Font asset without digest in Ruby on Rails 4

I've got a problem with my font assets being served without digest in production.
As soon as I do rake assets:precompile I get:
5futurebit-webfont-c133dbefd9e1ca208741ed53c7396062.eot
I was trying to link it with font-face in scss with asset-url, asset-path, font-url and font-path but all of them end up outputting path:
/assets/5futurebit-webfont.eot
For now I'm copying assets from /app/assets/fonts straight to /public/assets/ but it doesn't feel like that's the way to do it.
I've been looking at a similar issue and am currently using the non-stupid-digest-assets gem: https://github.com/alexspeller/non-stupid-digest-assets
For more info on how you can use it, see here.
Correct use of non-stupid-digest-assets gem
Now that being said, the link provided by Chris (specifically, https://stackoverflow.com/a/17367264/291640) seems like it may accomplish the same as the gem without the gem itself. I know I need to look into it further.
Make sure you have the exact filename WITH extention name of the font in your font-url declaration like:
Correct:
#font-face{
font-family: 'Sawasdee';
src: font-url('Sawasdee.ttf') format('truetype');
}
Wrong:
#font-face{
font-family: 'Sewasdee';
src: font-url('Sewasdee') format('truetype');
}
My font folder:
fonts
|_ Sewasdee.ttf
|_ Otherfont.ttf
Here is our solution, that is based partially on what Sprocets does. It is working with Rails4. It automatically generates a nondigest version for all assets, that were listed in config.assets.precompile, after precompilation was done.
# lib/tasks/assets_nondigest.rake
require 'fileutils'
namespace "assets:precompile" do
desc "Create nondigest versions of defined assets"
task :nondigest => :environment do
sprocket_task = Sprockets::Rails::Task.new ::Rails.application
assets = ::Rails.application.config.assets.precompile
paths = sprocket_task.index.each_logical_path(assets).to_a +
assets.select { |asset| Pathname.new(asset).absolute? if asset.is_a?(String)}
paths.each do |path|
if asset = sprocket_task.index.find_asset(path)
copy_target = File.join(sprocket_task.output, asset.digest_path)
target = File.join(sprocket_task.output, asset.logical_path)
sprocket_task.logger.info "Writing #{target}"
asset.write_to target
asset.write_to "#{target}.gz" if asset.is_a?(Sprockets::BundledAsset)
end
end
end
end
Rake::Task['assets:precompile'].enhance do
Rake::Task['assets:precompile:nondigest'].invoke
end

Why is php_template_preprocess_page function not called in Drupal 6x?

From another forum I found the following example:
"I was looking for a way to pull node data via ajax and came up with the following solution for Drupal 6. After implementing the changes below, if you add ajax=1 in the URL (e.g. mysite.com/node/1?ajax=1), you'll get just the content and no page layout.
in the template.php file for your theme:
function phptemplate_preprocess_page(&$vars) {
if ( isset($_GET['ajax']) && $_GET['ajax'] == 1 ) {
$vars['template_file'] = 'page-ajax';
}
}
then create page-ajax.tpl.php in your theme directory with this content:
<?php print $content; ?>
"
This seems like the logical way to do it and I did this, but the phptemplate_preprocess_page function is never called ... any suggestions?
I figured it out for myself from a Drupal Support Theme Development page:
"Maybe this helps
leahcim.2707 - May 29, 2008 - 05:40
I was trying to get the same thing done and for me this works, but I'm not sure if it is the correct way as I'm still new to Drupal:
in "template.php" I added the following function:
function phptemplate_preprocess_page(&$vars)
{
$css = $vars['css'];
unset($css['all']['module']['modules/system/system.css']);
unset($css['all']['module']['modules/system/defaults.css']);
$vars['styles'] = drupal_get_css($css);
}
I think after adding the function you need to go to /admin/build/themes so that Drupal recognises the function."
The part in bold is what did the trick ... you have to re-save the configuration so it recognizes that you've added a new function to the template.

Go for Zend framework or Django for a modular web application?

I am using both Zend framework and Django, and they both have they strengths and weakness, but they are both good framworks in their own way.
I do want to create a highly modular web application, like this example:
modules:
Admin
cms
articles
sections
...
...
...
I also want all modules to be self contained with all confid and template files.
I have been looking into a way to solve this is zend the last days, but adding one omer level to the module setup doesn't feel right. I am sure this could be done, but should I? I have also included Doctrine to my zend application that could give me even more problems in my module setup!
When we are talking about Django this is easy to implement (Easy as in concept, not in implementation time or whatever) and a great way to create web apps. But one of the downsides of Django is the web hosing part. There are some web hosts offering Django support, but not that many..
So then I guess the question is what have the most value; rapid modular development versus hosting options!
Well, comments are welcome!
Thanks
You can implement sub-modules with relatively little effort in ZF. Let's say you have directory structure such as:
application/
modules/
admin/
cms/
controllers/
views/
controllers/
views/
You'd register the modules like this in your bootstrap (sub-modules use _ to separate the sub-module from the main module):
$frontController->setControllerDirectory(array(
'default' => APPLICATION_PATH . '/modules/default/controllers',
'admin' => APPLICATION_PATH . '/modules/admin/controllers',
'admin_cms' => APPLICATION_PATH . '/modules/admin/cms/controllers'
));
The issue with this is that it would actually use an underline in the URL instead of a slash, so eg: "admin_cms/conteroller/action" instead of "admin/cms/controller/action". While this "works", it's not pretty. One way to solve the issue is to provide your own route for the default route. Since the default Zend_Controller_Router_Route_Module does it almost right, you can simply extend from it and add the wanted behavior:
<?php
class App_Router_Route_Module extends Zend_Controller_Router_Route_Module
{
public function __construct()
{
$frontController = Zend_Controller_Front::getInstance();
$dispatcher = $frontController->getDispatcher();
$request = $frontController->getRequest();
parent::__construct(array(), $dispatcher, $request);
}
public function match($path)
{
// Get front controller instance
$frontController = Zend_Controller_Front::getInstance();
// Parse path parts
$parts = explode('/', $path);
// Get all registered modules
$modules = $frontController->getControllerDirectory();
// Check if we're in default module
if (count($parts) == 0 || !isset($modules[$parts[0]]))
array_unshift($parts, $frontController->getDefaultModule());
// Module name
$module = $parts[0];
// While there are more parts to parse
while (isset($parts[1])) {
// Construct new module name
$module .= '_' . $parts[1];
// If module doesn't exist, stop processing
if (!isset($modules[$module]))
break;
// Replace the parts with the new module name
array_splice($parts, 0, 2, $module);
}
// Put path back together
$path = implode('/', $parts);
// Let Zend's module router deal with the rest
return parent::match($path);
}
}
And in your bootstrap:
$router = Zend_Controller_Front::getInstance()->getRouter();
$router->addRoute('default', new App_Router_Route_Module);
What this does is traverse the path as long as it finds a module, and transparently rewrites the path so that the default Zend_Controller_Router_Route_Module can do the real work. For example the following path: "/admin/cms/article/edit" will be transformed into "/admin_cms/article/edit", which allows the standard convention of the ZF's ":module/:controller/:action" do the magic.
This allows you to have nice modular structure with self-contained modules, while still use pretty, logical URLs. One thing you want to make note of is that if you use Zend_Navigation and specify the navigation items using module/controller/action parameters, you need to tell ZF how to correctly build the URL using "/" instead of "_" in module names (by default ZF uses the :module/:controller/:action spec when it builds the URLs). You can do this by implementing your own Zend_Controller_Action_Helper_Url, like this:
<?php
class App_Router_Helper_Url extends Zend_Controller_Action_Helper_Url
{
public function url($urlOptions = array(), $name = null, $reset = false, $encode = false)
{
// Replace the _ with / in the module name
$urlOptions['module'] = str_replace('_', '/', $urlOptions['module']);
// Let the router do rest of the work
return $this->getFrontController()->getRouter()->assemble($urlOptions, $name, $reset, $encode);
}
}
And in your bootstrap:
Zend_Controller_Action_HelperBroker::addHelper(new App_Router_Helper_Url);
Now Zend_Navigation works nicely with your sub-module support as well.
I (despite of being happy ZF user) would go for Django. In ZF the "fully-modular" application is kind of holly grail. It's nearly impossible (or at least without extreme effort) to create selfcontained modules, instalable like "copy this folder into your modules directory" :) Not sure about Django, but from what I head it's simplier there...