In a try to get code cleaner, I thought I could write a service in a custom module and use its methods within mytheme.theme
, but obviously the preprocess functions signatures don't accept extra parameters.
In modules/custom/custom_module/src/Service/FooThemeHelpers.php
namespace Drupal\custom_module\Service;
class FooThemeHelpers
{
// Add a specific custom format
public function format_profile_adresse($field_profile_adresse){
// do stuff ...
return $markup;
}
}
Then in mytheme.theme
use Drupal\custom_module\Service\FooThemeHelpers;
function mytheme_preprocess_views_view_fields(&$variables, FooThemeHelpers $themeHelpers) {
if($variables['view']->id() == 'bar') {
$markup = $themeHelpers->format_profile_adresse($variables['fields']['field_profile_adresse']->content);
$variables['fields']['field_profile_adresse']->content = $markup;
}
}
TypeError: Argument 2 passed to mytheme_preprocess_views_view_fields() must be an instance of Drupal\custom_module\Service\FooThemeHelpers, string given
I tried also with template_preprocess_page_title()
, same error.
Should I declare and use static methods instead in my service ? Is there any Drupal coding standard way to export these helpers functions in a dedicated class, so that .theme remains lighter and readable... ?