Preprocess data such that locations within a rectangle drawn on a map can be found in less than O(n) time

I came across this problem online and found no solutions or insight. The problem is stated as:

Given a map as a square, and a set of locations on the map, users are able to select a rectangle on the map and all of the locations on the map are returned How would you preprocess the map data so that the find operation for the locations in the inner rectangle can be done in less than O(n) time?

I’m really stumped on this as the only thing I could think of is to create a hashmap that contains every single possible rectangle within the map with values that are lists of locations within said rectangle. However, it would not be practically feasible to store that much data.

Any help would be appreciated!

Passing variables between theme preprocess hooks

i’m a newbie to drupal 8 and php coding in general so i hope my approach is not too much out of the lines. I’m trying to theme some parts of my website by fiddling a bit with templates, what i need to do is to get a value of a specific preprocess hook function and pass it to another one, to be more precise i need to print the page title of the currently visualized wizard page of my webform into the Page Title block, so it would show both the form main title and the current page title, basically generate a twig variable to put inside my page-title.html.twig template.

to get that value i’ve been doing the following:

function MYTHEME_preprocess_webform(&$  variables)   {   //Gets the current wizard page id   $  current_page = $  variables['element']['progress']['#current_page'];   //gets its correspondig value   $  page_title = $  variables['element']['elements'][$  current_page]['#title'];   $  variables['page_title'] = $  page_title;   } 

But of course the value {{ page_title }} would only be avaible inside the webform.html.twig template and not inside the page-title.html.twig template.

Is there a way to have those variables avaible inside the MYTHEME_preprocess_page_title hook instead? Or is there a better approach?

Get Username from UID with Preprocess for Template

I’m a bit lost at finding the username based on the uid. I get the uid from the address using:

  $  current_path = \Drupal::service('path.current')->getPath();   $  urluid = (explode("/",$  current_path));    $  us = \Drupal::entityTypeManager()->getStorage('user')   ->loadByProperties(['uid' => $  urluid[2]]);    kint($  us); 

returns an array of data where i do see the uid, but not the username for that uid. Name:

'name' => array(1) *DEPTH TOO GREAT* 

returns NULL:

kint($  us->name); 

I’d like to return the UID->Name as the title on the ROLES and EDIT screens for the user. Exactly how it is returned for VIEW (example dvweb is: /user/10): d

Strip html tags in preprocess hook

We have a mytheme.theme file that has a mytheme_preprocess_node(&$ variables) function. Within this preprocess hook, we would like to remove all HTML tags within a formatted (long) field. The goal is to do without using striptags within the node--page.html.twig template.

How can we do this securely without using striptags in a twig template?

Here is what we tried, but cannot find how to do it using mytheme_preprocess_node hook.


function mytheme_preprocess_node(&$  variables) {    $  node = $  variables['node'];   $  field_value = $  node->get('body')->first()->getValue()['value'];   ksm($  field_value);   // cannot find way to remove `html` tags } 

output of ksm($ field_value)

"& lt;p & gt;When looking at & lt;a href=""& gt;article trends& lt;/a& gt; over time, attacks are cyclical in nature. Attackers develop new attack types and vectors, which are used to launch a new wave of attacks. As defenders become more proficient in stopping these new attacks, the attackers develop new types of attacks and the cycle repeats itself.</p& gt; 

In order to properly display the output, I had to a space between & and lt characters above because StackExchange will convert those to proper tags. Within the ksm statement there is no space.

Passing data from outer preprocess to inner template

I have two templates: – a child that is printing each item in a list; – and a parent that calls it there is also an intermediate Field template that is not involved.

The parent has preprocess access to node field data that each child (node teaser) call needs to use. The child is printing items in a multivalue entity reference field.

How can the child get the data from the parent felds so it can print the right html?

is it okay to use an external system to preprocess text before indexing it to elasticsearch?

so my problem is: I have a lot of pdf & docx documents and my task is to build an indexing plateform that helps us search documents by typing keywords

What i did: i stored these files in hadoop, and created a spark job that parses these files, preprocess the text (remove punctuation, toLowerCase, remove stopwords,… )

i used the preprocessed text in two things:

  1. perform clustering using Spark mLib (this is out of the scope of the question)
  2. index it to elasticsearch, so i can perform later the search by keywords

so my problem here is with the second point:

  • is it okay to send an already preprocessed text that doesn’t contain stopwords to elasticsearch, knowing that elasticsearch itself is able to preprocess text and remove stopword ?

  • Or is there any performance advantages in doing so ?

Final question is about the whole approche of indexing documents by only creating indexes based on keywords

  • is it the right thing to do ?

Using cache for twig variables in preprocess function

I implement a menu on a region using a preprocess function to get a link with an anchor for each block of it with a title. I made a preprocess function for region, in my theme, where I test the region machine name.

I first used the $ variables[‘elements’][XXX][‘#id’] to load each block, to find out if the label was set to be display. But I quickly discover that on my server, where the cache is on, the $ variables[‘elements’] only contain an array of cached render.

I then modify my preprocess hook to use the key of the $ variables[‘elements’], witch is finally the block key.

use Drupal\block\Entity\Block;  /**  * Implements hook_preprocess_region().  */ function MYTHEME_preprocess_region(&$  variables) {   if ($  variables['region'] == 'one_page') {     $  blocs_menu = array();     foreach ($  variables['elements'] as $  key => $  values) {       if (substr($  key, 0, 1) == '#') {         continue;       }       $  bloc_object = Block::load($  key);       if (is_object($  bloc_object)) {         $  bloc_settings = $  bloc_object->get('settings');         if ($  bloc_settings['label_display']) {           $  blocs_menu[] = array(               'id' => $  key,               'label' => $  bloc_settings['label'],           );         }       }     }     if (count($  blocs_menu)) {       $  variables['region_menu'] = $  blocs_menu;     }   } } 

And in my override file region–one-page.html.twig

{%- if region_menu -%} <nav class="page-nav-anchor">   <ul> {%- for menu in region_menu -%}   <li><a rel="scroll" href="#block-{{ menu['id'] }}">{{ menu['label'] }}</a></li> {%- endfor -%}   </ul> </nav> {%- endif -%} 

Everything is working well, but I would like to improve the concept :

  • Be able to detect if the cache is activated on the project
  • Include in cache my ‘region_menu’ variable, and generate it only when cache have to be rebuild.

If I understand well, the twig template is also cached, then it is maybe just not really necessary to declare the menu if cache is ON ?

The thing is I’m really lost in the D8 cache API. I think I have to deal with the cache tags, because I don’t have a render to cache.

I would appreciate some help, I cannot find some good (and easy) examples on the documentation or in the core modules.

Preprocess Menu Link Independent of menu.html.twig?

I am hoping there is a way to alter a menu link independent of menu.html.twig

Motivation is this example from Bootstrap theme menu.html.twig:

{% set link_title = item.title %} {% set link_title %}{{ link_title }} <span class="caret"></span>{% endset %} 

The Twig template is adding markup to the link $ variables['text'] of hook_link_alter().

I’m altering the text of a menu link item but retaining any HTML it might have. I have the below which works:

function hook_link_alter(&$  variables) {    $  linkText = $  variables['text'];   $  cleanLinkText = rtrim(strip_tags($  linkText));    if ($  cleanLinkText == 'string') {      $  linkMarkup = str_replace($  cleanLinkText, '', $  linkText);      // c_Markup() returns a new TranslatableMarkup().     // We have to pass back in the HTML.     $  markup = c_Markup($  linkMarkup);      $  variables['text'] = $  markup;    }  } 

Things like str_replace and trim are very powerful, but I would prefer I use the appropriate hook for the need.

Have worked with hook_preprocess_menu(&$ variables, $ hook) without better success.

Pass a variable from a block preprocess hook to a twig template that inserts that block

I use the D8 book module to manage magazines and their articles.

In the node--magazine.html.twig template for a magazine, I use the built-in book_navigation block to add a table of contents. This is done by drupal_block("book_navigation", {block_mode: "book pages"}). Works fine.

For certain “featured” articles in the table of contents, I want to display an image. I use THEME_preprocess_book_tree(&$ variables) to add the image url to the items array in $ variables. I’ve sub-themed book-tree-html.twig to get the image url from the items array and include the image in the table of contents. Works fine.

BUT, I need to know in node--magazine.html.twig whether there are any featured articles in the table of contents to present a proper heading on the page.

QUESTION: What is the best way to pass a variable from THEME_preprocess_book_tree() to node--magazine.html.twig? It’s not a direct connection. Getting preprocess variables in book-tree.html.twig is easy, but I need to pass a variable through to node--magazine.html.twig, where the book tree is inserted.

What I have tried:

  • In the book-tree.html.twig template, if there is a featured article, I add a hidden “featured-article” label to the html and then in the magazine template, I test for its presence via {% if "featured-article" in <rendered block html> %}. This works, but it feels unsavory.

  • In THEME_preprocess_book_tree(), I add $ variables['featured'] = "test"; and in the magazine template I {{ dump(featured) }}. This doesn’t work. I just get NULL. I’m not sure what–if any–connection there is between the $ variables array available in the preprocess hook and variables available in the magazine template.

  • In THEME_preprocess_book_tree(), I could set a global variable and then in the magazine template, call a custom twig extension to check the value of that variable. I haven’t tried this yet, but it seems like this should work. Just seems like there should be a more elegant way.

How to replace a preprocess function entirely?

I need to replace template_preprocess_links with my own preprocess function and I can’t find in the documentation how to replace a preprocess function entirely. Here is my current HOOK_theme implementation:

/**  * Implements hook_theme().  */ function my_module_theme($  existing, $  type, $  theme, $  path) {       return [     'links' => [       'variables' => [         'links' => NULL,         'raw_links' => NULL,         'attributes' => NULL,         'heading' => NULL       ],       'override preprocess functions' => TRUE     ]   ]; } 

But even with override preprocess functions set to TRUE, the core template_preprocess_links is still called and pollute the output with rendered links.

How can I replace this preprocess function entirely?