How to add a local Twig extension from a controller - symfony

I have a very specialized filter I want to use for a single page without making it a global filter. I tried doing this (that isn't the function I want, it's just a test):
$this->get('twig')
->addFilter(new \Twig_SimpleFilter('chgname', function ($string) {
return substr($string, 0, 5);
}));
But I get an error, "Unable to add filter as extensions have already been initialized".
I know that I can create a class in the AppBundle/Twig directory and add it as a service, but 1) That's incredibly heavy and a PITA for just a simple filter that I need, and 2) It makes it global to the entire application, which is dumb for something I need locally.
Is there any way to do this, or am I stuck with only global extensions? Thanks in advance.

Twig loads an environment when your app boots and you cannot dynamically change it.
if you think Symfony is too heavy you can still take a look at Silex (which uses Symfony components) so you could write something like :
$app['twig'] = $app->extend('twig', function ($twig) {
$twig->addFilter(new \Twig_SimpleFilter('chgname', function ($string) {
return substr($string, 0, 5);
}));
return $twig;
});
see http://silex.sensiolabs.org

Related

using export in alloy controller versus attaching functions directly to the '$' scope

here is the code of an alloy controller written in two different ways. Although the both work the same, Which one might be best practice?
example 1 of controller.js:
var currentState = true;
$.getState = function(){
return currentState;
}
example 2 of controller.js:
var currentState = true;
exports.getState = function(){
return currentState;
}
Titanium is based on the CommonJS framework. The exports variable is a special variable used typically to expose a public API in a class object. So when you want to expose a method of doSomething() on the MyModule.js class you would use the exports variable like this:
exports.doSomething() = function(args) {
//Some really cool method here
};
Then reference that class using
var myModule = require('MyModule');
myModule.doSomething();
However when referencing a view object the typical way to reference the is using the $. shortcut. You can see they prefer that method in the official documentation.
http://docs.appcelerator.com/platform/latest/#!/guide/Alloy_XML_Markup
The $ variable holds a reference to your controller instance. It also contains some references to all indexed views (understand, views for which you supplied an index in you xml markup).
Both ways are strictly equivalent as, during the compilation, Alloy will merge the content of the exports with your controller referenced in $. Adding them directly to the instance won't change a thing.
Neverthless, developers are used to see the public API as the set of functions exported via the special variable exports; Thus, I will recommend to keep using it in a clean and clear way (for instance, defining your functions in your module scope, and only expose them at the end or beginning of your controller).
function myFunction1 () { }
function myFunction2 () { }
function myFunction3 () { }
exports.myFunction1 = myFunction1;
exports.myFunction3 = myFunction3;
Thereby, your API is quite clear for people diving into your source code. (A readMe file is also highly recommended :) ).

getting the gettext behavior using the Po File Loader in the translation provider in Silex

I'm using the translation provider and the PoFileLoader in Silex and everything works super great.
$app['translator'] = $app->share($app->extend('translator', function($translator, $app) {
$translator->addLoader('po', new PoFileLoader());
$translator->addResource('po', __DIR__.'/resources/translations/de.po', 'de');
}
The only problem that I have is how it treats strings that doesn't have translation yet. I want them to be ignored and use the source instead of an empty string. Like the way gettext function treats the po files.
Is there any option for that or should I override the PoFileLoader class?
The only problem that I have is how it treats strings that doesn't have translation yet. I want them to be ignored and use the source instead of an empty string. Like the way gettext function treats the po files.
This is something the translator does, not the file loader. If there is no translation found in the message catalogue, the translator will just replace the parameters and return the source.
See also the source:
public function get($id, $domain = 'messages')
{
// ... all the loading logic
// if everything failed, just return the source
return $id;
}
This method is called in the Translator#trans method.

Meteor helper methods

I want to write some helper functions that I can use in my other JavaScript files.
It says here:
Some JavaScript libraries only work when placed in the client/compatibility subdirectory. Files in this directory are executed without being wrapped in a new variable scope.
It seems a bit bizarre to me that I should have to throw all my libraries in a folder called compatibility. Generally "compatible" stuff is for legacy code that hasn't been upgraded to the new style. Is there no way to export modules so that I can access them in my other files?
Using this pattern now:
Util = (function(exports) {
exports.getFileExtension = function(filename) {
var i = filename.lastIndexOf('.');
return (i < 0) ? '' : filename.substr(i);
};
// more functions
return exports;
})(typeof Util !== 'undefined' ? Util : {});
Not sure if that's the best or not...but it appears to work.
It would be bizarre, you are right. Write your own code, just put it somewhere and it works. This refers to complicated frameworks that make a lot of functions all over the place, where no one has 'tamed' them to only expose a root object that all its powers spring from.
Please read "Namespacing and Modules" at
http://www.meteor.com/blog/2013/08/14/meteor-065-namespacing-modularity-new-build-system-source-maps
It's helping you with built in maintainability for avoiding collisions with other things you write, which is largely what namespaces is for.
A good practice is to have your own helper object, named helper or util, where you put grouped things:
utils = {
distance_between: function(lat1,lng1,lat2,lng2) {
var radiusEarth = 3963.1676; // miles radius earth
var dLat = deg2rad(lat2-lat1); // deg2rad below
...
displayHumanReadableTime: function(timestamp){
var a = new Date(timestamp);
If the intention is to write Utility method then it can be written using the ECMA6 Script standard.
Write your method by exporting once in method.js and use it by importing in the desired file(s)
Ex:
export const MyUtilityMethod = function (){...} in /method.js
import {MyUtilityMethod} from './method.js'
Hope this helps.

Flex: Which way should I add this event handler?

I use a unit of work pattern a lot in my flex projects. I'll have a class that might call a web service, put the data in a sqlite db, refresh a model with the data then raise an event.
I usually call these inline and pass in some singleton classes:
protected function CareerSynced():void
{
var process:ProcessWorkouts = new ProcessWorkouts(_dataModel, _trainerModel, _databaseCache, _database.Conn);
process.addEventListener("AllWorkoutsProcessed", AllWorkoutsProcessed);
process.UpdateAllUnprocessed();
}
I'll then get the response like this:
private function AllWorkoutsProcessed(event:DataReceivedEvent):void
{
//do something here
}
My question is, am I adding that event listener correctly? I think I might be causing a memory leak, but I'm not sure. I've also thought about using a weak reference. I'm confused about when to use them. Would this be one of those cases?
Should it be like this?
process.addEventListener("AllWorkoutsProcessed", AllWorkoutsProcessed,false, 0, true);
I would either go with the weak reference or just remove the listener:
private function AllWorkoutsProcessed(event:DataReceivedEvent):void
{
event.target.removeEventListener("AllWorksoutsProcessed",AllWorkoutsProcessed);
}
I could list out my reasons but I'll just point you to this.

When does the $op parameter of hook_search() get defined as 'search'?

Edit
The basic question here is "when does the $op parameter get defined as 'search'"?
I am trying to create a custom search in an implementation of hook_search(). I have been looking through the Drupal documentation for the method here: http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_search/6
I know the method is running because I can slip a die('killed inside of implementation of hook_search()') into the top of the function and see the output.
In the following code, the script is never killed so that I can see the output search caught inside of my_search(). This leads me to believe that the 'search' case of the switch statement is never firing. Does anybody know where I might go from here?
/**
* Implementation of hook_search()
*/
function my_search($op = 'search', $keys = NULL) {
switch($op)
{
case 'search':
die('search caught inside of my_search()');
break;
}
}
First things first.
Assuming your module is called 'my', try to go to URL /search/my/whatever - probably you will see access forbidden page (assuming you do not have anything more in your code besides what you have pasted in your question).
That's because you do not return anything when search module calls your hook with $op = 'name' (see _search_menu() in search.module). You need to return "a translated name defining the type of items that are searched for with this module ('content', 'users', ...)" - see http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_search/6 And access forbidden gone.
Once this is done, search will call your hook again (actually, there are quite a few calls, you can for example drupal_set_message($op) in your hook to see them all), and one of those calls will be with $op = "search" as well (coming from search_data() in search.module).

Resources