Adding custom code to <head> in Drupal - drupal

I'm trying to figure out where the <head> for all of the pages in Drupal is (I'm using Orange theme if it matters). I have to add analytics code into the <head>.
Inside which file would I find the <head>?

Use drupal_set_html_head() by placing this in your themes template.php file. If the function MYTHEMENAME_preprocess_page() already exists insert what is inside the {closure} brackets below (before the $vars['head'] if that exists in it as well) :
function MYTHEMENAME_preprocess_page(&$vars, $hook) {
// say you wanted to add Google Webmaster Tools verification to homepage.
if (drupal_is_front_page()) {
drupal_set_html_head('<meta name="google-site-verification" content="[string from https://www.google.com/webmasters/verification/verification]" />');
$vars['head'] = drupal_get_html_head();
}
}

In template.php of your theme folder :
function your_theme_preprocess_html(&$variables) {
$appleIcon57px = array(
'#tag' => 'link',
'#attributes' => array(
'rel' => 'apple-touch-icon',
'href' => '/images/ICONE-57.png',
'type' => 'image/png',
'media' => 'screen and (resolution: 163dpi)'
)
);
drupal_add_html_head($appleIcon57px, 'apple-touch-icon57');
}

If you look in your theme folder you'll see page.tpl.php, that is the template for the site. You can add the code there most likely.

How to change a page meta description and keywords in Drupal 6

One another solution is to use blocks in header these can also managed very effectively using css.
All you have to do is to go to Structure->Blocks then create new block.
Then select theme corresponding to it and position in which section you want to show that block.
Custom html like can be added. And can be handled from that id.
It allow me to handle page structure very easily.

In the theme folder (e.g. themes/orange) there is a templates folder with the file html.tpl.php
In this file you can freely add what you need to the head section and it will be added to every page.

there is a google analyitics module that will accomplish this for you with just your key.

Related

Drupal: Password textfield in everypage, how can I remove?

After migration, every page add password textfield at the end of every page.
What is this? How can I remove or troubleshoot?
Drupal 7.27 with apache 2.4 and php 7.0 (same problem with php 5.6.35).
Look there is a script loaded on these pages (just above the <form> itself) that creates the input tags and set the windows focus in it :
<script type="text/javascript">
var d = document;
d.write("<br><br><form method='post'><center><input type='password'...>...");
// ...
</script>
You want to remove this script.
Since there are several ways to include javascript with Drupal it may be difficult to spot the code responsible for that. Given the ugliness of the script itself, it could very well be harcoded in a theme template file (in this case, theme switching during migration would explain why your issue suddenly arose).
The chance is that ugly snippets like this is quite often hardcoded so you can make a search for a part of the js string (e.g. 'd.write("<br><br><form') in your project at the root of your site and/or in sites/all.
Lastly, find the guy that wrote this and beat him ;)
Your code is including a java script in every page which is creating input type password since it is included in every page that's why you are getting this field.
kindly check your requirement for same.
In drupal We can add JS in drupal by following method
1.)By drupal_add_js() function
drupal_add_js() is drupal api function to include js.
Example:
drupal_add_js('misc/collapse.js');
// add JS file
drupal_add_js('misc/collapse.js', 'file');
// For including inline javascript
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
//For including inline javascript and includ and includ it in footer
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', array(
'type' => 'inline',
'scope' => 'footer',
'weight' => 5,
));
//For including External JS
drupal_add_js('http://example.com/example.js', 'external');
//For passing php value to JS
drupal_add_js(array(
'myModule' => array(
'key' => 'value',
),
), 'setting');
Example:
drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
for more infomation visit https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7.x
2.)Adding by Form API
we can used '#attached' property of form api for including js
Example:
$form['#attached']['js'] = array(
drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
);
3.)Adding JS in info file
We can including javascript in script file
Example:
name = My theme
description = Theme developed by me.
core = 7.x
engine = phptemplate
scripts[] = mytheme.js
4.)By preprocess function
if we want to conditionaly include JS we can include it in preprocess function
function mytheme_preprocess_page(&$vars, $hook) {
if (true) {
drupal_add_js(drupal_get_path('theme', 'mytheme') . '/mytheme.js');
$vars['scripts'] = drupal_get_js(); // necessary in D7?
}
}

Working with forms in drupal 8

I am facing problem with "#markup" in form API.
In Drupal 7 we can use "#markup" form element which look like this:
<?php
$form['test'] = array(
'#type' => 'markup',
'#markup' => '<div><script src="http://localhost/drupal7/sites/all/libraries/test.js"></script></div>',
);
?>
//Here is my custom test.js
(function($) {
Drupal.behaviors.test = {
attach: function(context, settings) {
console.log('testttt');
document.write('*Hello, there!*');
}
};
})(jQuery);
and above code will print "Hello, there!" when form will be render.
Now in Drupal 8 I am using below code but it prints nothing.
<?php
$form['test'] = array(
'#markup' => '<div><script src="http://localhost/project8/sites/all/libraries/test.js"></script></div>',
);
?>
So how can implement this functionality in Drupal 8, which is already working in Drupal 7 .
Under script tag it can be local script or external script..
Please help...
Thanks
In Drupal 8, using "#markup" is not the proposed method to attach javascript files.
You can define libraries in your custom module or theme and attach the library to your form. The library can contain multiple js and (or) css files.
To define a library in your module:
Suppose your module name is "my_module", create a file "my_module.libraries.yml" in your module folder and specify the js and css files like this
form-script:
version: 1.x
css:
theme:
css/form.css: {}
js:
js/form.js: {}
js/form-ajax.js: {}
dependencies:
- core/jquery
In order to attach this library to your form:
$form['#attached']['library'][] = 'my_module/form-script';
Then clear cache. The js and css files will be loaded in the same order as you mentioned in the libraries.yml file.
You can define multiple libraries in the same "my_module.libraries.yml" file.
#markup still works in Drupal 8, but now it is filtered before output. As it is stated in Render API overview:
#markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, and are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Aternatively, you can use the render array key #allowed_tags to alter which tags are filtered.
As an alternative you may use FormattableMarkup:
'#markup' => new FormattableMarkup('<div><script src="http://localhost/project8/sites/all/libraries/test.js"></script></div>', []),
though it is not recommended in this case.

How can I set/remove meta tags?

How do I add meta tags or remove them, for example the default ones added by Drupal core?
I have added the meta tags currently just to the html.html.twig file.
There seems to be module which is in beta stage, but if possible, I would like to avoid using third-party modules for this, at the moment.
The Meta tags module requires you to install three modules:
Meta tags: http://drupal.org/project/metatag
CTools: http://drupal.org/project/ctools
Token: http://drupal.org/project/token
You will see that the Meta Tags module comes with additional modules you can enable it.
Configure Meta Tags Module
Click on Configuration in the black admin menu bar
Click on Meta tags in the Search and Metadata box on the left side of the screen.
Notice there are four global settings.
Click on each and observe what you get by default. All nodes, terms, and users will have the same configuration by default. But that doesn't have to be the case.
Now add default Meta Tag.
Click on Add a meta tag default.
Selet Article from the Type dropdown. Enter the token [node:content-type:description] in the abstract field. Save When you create an Article node from now on, the description of the Article content type will appear as such:
Now its time to enter the meta tag data with in the site.
These are some of the basic steps you can follow to add Meta Tag in Drupal. Please follow the steps and let me know if there are any other issue you get.
(Credit: https://www.ostraining.com/blog/drupal/meta-tags/)
Enable the modules
The Meta tags module requires you to install three modules:
Meta tags: http://drupal.org/project/metatag
CTools: http://drupal.org/project/ctools
Token: http://drupal.org/project/token
You will see that the Meta Tags module comes with additional modules you can enable, depending on the needs of your site.
You can also just use the THEME_preproces_html hook in your theme's .theme file to add a META-TAG
for example:
function THEME_preprocess_html(&$variables) {
$viewport = [
'#tag' => 'meta',
'#attributes' => [
'name' => 'viewport',
'content' => 'user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1',
],
];
$variables['page']['#attached']['html_head'][] = [$viewport, 'viewport'];
}
Will get you this:
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
A bit late maybe. But if you just want to get rid of these meta-tags, you can do it simply in your THEMENAME.theme file:
function YOURTHEMENAME_page_attachments_alter(array &$page) {
$unset_meta = [
'system_meta_generator', // Generator tag
'MobileOptimized', // MobileOptimized tag
'HandheldFriendly', // HandheldFriendly tag
];
foreach ($page['#attached']['html_head'] as $key => $value) {
if (in_array($value[1], $unset_meta)) unset($page['#attached']['html_head'][$key]);
}
}

Use custom module to insert tags before page content on Drupal

I'm trying to create a Drupal custom module that would enclose any page or article content with specific microdata tags (among other things). I've successfully inserted code in both the header and before the closing '' tag, but when I try to enclose the page content it just jams everything together at the end of the content.
For example, here's the module code:
function my_module_page_build(&$page) {
// add manifest value to header
$manifest_code = "..."
$page['header']['manifest'] = array(
"#weight" => 0,
"#markup" => t($manifest_code)
);
// add opening microdata tags
$opening_microdata = "...";
$page['content']['my_module_open_microdata'] = array(
"#weight" => 0,
"#markup" => t($opening_microdata)
);
$closing_microdata = "...";
$page['content']['my_module_close_microdata'] = array(
"#weight" => 25,
"#markup" => t($closing_microdata)
);
// add javascript to footer
$javascript = "...";
$page['page_bottom']['my_module_javascript'] = array(
"#weight" => 0,
"#markup" => t($javascript)
);
}
I don't want to insert the closing microdata into the $page['page-bottom'] slot because I don't want some of these links and other code inside the microdata tags. I've also tried using a negative weight to move it up, but no luck.
I've tried searching for more information on Node or Blog or Article structure to see if there are other slots for the code, but I can't find anything.
I'm sure this is very easy -- are there resources I'm missing for understanding page structure? Some simple solution I'm missing?
Two potential solutions:
Try the tip from the first comment on hook_page_build, which should make your weight declarations actually take effect. (Not sure if resetting the #sorted flag might have adverse effects, though.)
Switch from using hook_page_build() to your_module_preprocess_page(&$variables), adding your microdata tags and other stuff as custom entries to the ´$variables´ array there. Then adjust your page template to place these additional variables as you please. This gives you pretty decent control over the placement of your additions, at the price of being tied to theme customizations (i.e. it works well for custom site building, but not so well if your module is intended for general usage with arbitrary themes).

Drupal 7 and using custom templates with theme()

I have a list of items in the default main-menu. I am trying to override the template so I may iterate over each item and custom template/theme the entire menu.
echo theme('links', array('links' => menu_navigation_links('main-menu', 0)));
main-menu is the default menu ID drupal provides. The first param to theme is telling it to use the default "links" template - this much I understand. How do I tell it to use MY mainmenu.tpl.php that resides in mytheme directory?
I have tried creating a file named mainmenu.tpl.php and calling it with
theme('links__mainmenu.tpl.php')
So as to provide a fallback to default links in case mainmenu.tpl.php should every disappear. I am naming the files wrong or something and I cannot for the life of me figure it out. Help :)
Cheers,
Alex
A module's default theme is defined in the hook_theme method. This function allows you to declare theme files (.tpl.php) and the variables passed to them. To declare the default theme file, use the template field.
function hook_theme($existing, $type, $theme, $path) {
return array(
'mymodule_display' => array( /* displayable name */
'template' => 'mymodule_display', /* template file, leave off .tpl.php */
'variable' => array(...), /* associative array of vars used */
)
);
}
This link contains a more in depth example.
To invoke the module's default theme, use the theme() method, as shown in your original post. Something like:
<?php echo theme('mymodule_display', array(/* vars */));
The double-underscore is used for defining fallback themes, with the last one being preferred. Therefore, theme('links__mymodule_display', ...) means that Drupal will use the Links module theme only if mymodule_display cannot be resovled.
Kind of basic but does your theme implement the base theme and is your theme set to the default?

Resources