Custom 404 template file in Drupal 8 - drupal-theming

How can I create a custom 404 page in Drupal 8?
I have created a new page(Content) in the backoffice called 404 (node number 100).
I have set it as the 404 default page at Configuration >
Basic site settings.
It works with the content that I have set in the Backoffice.
But now I want it to be editable programatically and I don't know how can I create the overriding file.
I have tried to create mytheme/templates/html--node--100.html.twig and it works only when the request its directly that url (node/100), but it doesn't work when you try a random slug on the URL and drupal has to resolve it. When this happens, drupal is serving me the content that the 404 page has in the backoffice and not in the file that I have just created.
I have tried several files like page--404-html.twig, html--node--404.html.twig, html--page--404.html.twig,... but it doesn't work neither
Can anyone lend me a hand?

page--system--404.html.twig (or the equivalent for other 4xx statuses) no longer works in Drupal 8.3 as the 4xx response handling has changed. You'll now need the core patch from https://www.drupal.org/node/2363987 or a similar custom module hook that adds template suggestions for these pages:
/**
* Implements hook_theme_suggestions_page() to set 40x template suggestions
*/
function MYMODULE_theme_suggestions_page(array $variables) {
$path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
$suggestions = theme_get_suggestions($path_args, 'page');
$http_error_suggestions = [
'system.401' => 'page__401',
'system.403' => 'page__403',
'system.404' => 'page__404',
];
$route_name = \Drupal::routeMatch()->getRouteName();
if (isset($http_error_suggestions[$route_name])) {
$suggestions[] = $http_error_suggestions[$route_name];
}
return $suggestions;
}
EDIT: It's probably nicer to use hook_theme_suggestions_page_alter to modify the suggestions array. See an updated version of this code in https://www.drupal.org/project/fourxx_templates (or https://github.com/ahebrank/fourxx_templates/blob/8.x-1.x/fourxx_templates.module)

The following implementation adds a template suggestion for page, in this case if you create a page--404.html.twig file in your theme, you'll be able to customize the page and works with Drupal 8.5.1
MYTHEME.theme
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function MYTHEME_theme_suggestions_page_alter(&$suggestions, $variables, $hook) {
/**
* 404 template suggestion.
*/
if (!is_null(Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'))) {
$status_code = Drupal::requestStack()->getCurrentRequest()->attributes->get('exception')->getStatusCode();
switch ($status_code) {
case 404: {
$suggestions[] = 'page__' . (string) $status_code;
break;
}
default:
break;
}
}
}
and create a template called page--404.html.twig and override with your stuff.
OR,
if you want to add suggestions for all error pages, just take out the switch statement.
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function MYTHEME_theme_suggestions_page_alter(&$suggestions, $variables) {
/**
* error page template suggestions.
*/
if (!is_null(Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'))) {
$status_code = Drupal::requestStack()->getCurrentRequest()->attributes->get('exception')->getStatusCode();
$suggestions[] = 'page__' . (string) $status_code;
}
}

You can now use page--404.html.twig. Just be sure you don't set a node as the 404 page. Source: https://www.drupal.org/node/2960810

Try page--system--404.html.twig

Related

vBulletin 3.x - How to get custom variable to render template conditionals?

I am trying to make a product that will give me a different header based on the forum I am in, that's no problem and complete. My issue lays with using template conditionals inside of said option.
I am currently using a forum option to insert my custom template additions:
In global_complete hook I am using:
global $vbulletin;
if ($GLOBALS[foruminfo]["forumid"]>0) {
$forum_code = '';
$_fid = $GLOBALS[foruminfo]["forumid"];
$forum_info = $vbulletin->forumcache[$_fid];
if ($forum_info["code"]) {
$forum_code = $forum_info["code"];
} elseif ($forum_info["parentid"]) {
while ($forum_code=='' && $forum_info["parentid"]>0) {
$forum_info = $vbulletin->forumcache[$forum_info["parentid"]];
$forum_code = $forum_info["code"];
}
}
}
Then I place $forum_code into my header temple.
I would like to be able to get the conditionals to work so I can only show things to members or usergroups within the header. Is there a way to get the variable to not ignore the conditions? they are included in the DB entry, just being ignored when rendered to the page.
Sample Conditional:
<if condition="$show['member']">Member<else/>Guest</if>
What is actually being rendered:
MemberGuest

Load component/template depending on the route param vuejs

I would like to ask if can I implement this on vuejs, so basically the code will load a page/template base on the param url. I've been searching for a while and can't get the results I need or maybe I'm just searching a wrong keyword.
My url is like this, so I just can't manually declare the url in my route because it is dynamic, fetch from the database.
path: '/user/page_type
Thank you very much!
export default {
mounted () {
if(this.$routes.params.page_type == "home"){
// Load Homepage Here
// ../../../page/HomePage.vue
}
else if(this.$routes.params.page_type == "speaker"){
// Load Speakerpage Here
// ../../../page/HomePage.vue
}
else if(this.$routes.params.page_type == 'html'){
// Load HTML Page Here
// ../../../page/HtmlPage.vue
}
}
}
This is available out of the box within official addon vue-router.
Docs for your case: link

JS not loading php into div, website specific behaviour

I have two joomla applications se up with exactly the same versions, the same global configuration settings, and I set up a test application with the following function to load a php into a div on a specific page..
function getDiv(str) {
var id = document.getElementById("appselector").value;
if (id == "") {
document.getElementById("scoffitcategoryedit").innerHTML = "";
return;
}
else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp3 = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState == 4 && xmlhttp3.status == 200) {
document.getElementById("scoffitcategoryedit").innerHTML = xmlhttp3.responseText;
alert("WTF");
}
};
xmlhttp3.open("GET","index.php?option=com_jumi&fileid=23& format=raw&" + str + id, true);
xmlhttp3.send();
}
}
I know its a little long winded, but the problem is that the script works fine in one website, but not in the other. Both of them are loading the same versions of jquery (which as you can see I don't like using), and both have the same templates. The only clue I seem to have found is that when I have text links elsewhere on the site attached with query statements pointing to self (index.php?blastr=bla&drivelstr=drivel), the browser shows index.php/ prepended to the link mentioned above.
I debugged the script and in the non functioning website it hangs on the xmlhttp3.send line.
I know people espouse the beauty of jquery's load() function as a replacement for this, but I cant get it to work (probably because the templates are using jquery versions higher than 1.8.1 when it was deprecated). So i'd rather stick with base js.
Any ideas about this inconsistent behaviour ?
This should be a comment but can't yet :(
I would check your configuration file for this line:
public $live_site = '';
and see if there is something in the failing site besides ''.
I found out what it was, I must have actually installed two different versions of the Jumi application in my websites. one website had a file under components/com_jumi/views/application named view.raw.php while the other did not. This meant that the format=raw in the index.php string could not be interpreted and caused a null response.
I simply copied the file into the other website where it was missing and everything then worked fine. But thanks for the response.

Exception Error: chrome://app/content/app1.js - EXPORTED_SYMBOLS is not an array

"EXPORTED_SYMBOLS is not an array" Exception flagged when tried to use Components.utils.import("chrome://app/content/app1.js");.
I have a XUL application created and from one of the JS File(say app.js) I tried to include the other JS File as shown above.
Both app.js and app1.js are placed in content folder and also in chrome.manifest file following line is added
"content app content/"
In other JS File (app1.js), I have exported symbols like
var EXPORTED_SYMBOLS = ["Fooinstance"];
var Fooinstance = {
foo: function() {
...
}
}
In app.js,
Components.utils.import("chrome://app/content/app1.js");
// Error: chrome://app/content/app1.js - EXPORTED_SYMBOLS is not an array
...
Fooinstance.foo();
I am running this XUL app on XULRunner 17.0.1 win32 libraries.
I looked through the code in this link https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Using
It did not help and if I include it as resource it works however I do not want to include it as part of resource.
Could you someone point out what mistake would be ?
I had this same problem, and I solved it:
1) changing the file extension (.js) by .jsm
2) Adding a first line on your module exporting classes to share. EG:
var EXPORTED_SYMBOLS = ["Xobject"];
function Xobject(){
}
Xobject.prototype.stop = function() {
return 'stop';
}
Xobject.prototype.run = function() {
return 'running';
}
3) Calling this way
Components.utils.import('resource://gre/modules/Services.jsm' );
Components.utils.import("chrome://myFirstAddOn/content/Xobject.jsm");
var myXobject = new Xobject();
alert(myXobject.run());
Hope it help u
For anyone else getting this, another possible reason is a circular dependency. My case was a little different, but I had two JSM files each using Components.utils.import to import each other. Then I got this error in one of them.

Yii renderpartial (proccessoutput = true) Avoid Duplicate js request

Im creating a site who works with ajaxRequest, when I click a link, it will load using ajaxRequest. When I load for example user/login UserController actionLogin, I renderPartial the view with processOUtput to true so the js needed inside that view will be generated, however if I have clientScriptRegister inside that view with events, how can I avoid to generate the scriptRegistered twice or multiple depending on the ajaxRequest? I have tried Yii::app()->clientScript->isSCriptRegistered('scriptId') to check if the script is already registered but it seems that if you used ajaxRequest, the result is always false because it will only be true after the render is finished.
Controller code
if (Yii::app()->request->isAjaxRequest)
{
$this->renderPartial('view',array('model'=>$model),false,true);
}
View Code
if (!Yii::app()->clientScript->isScriptregistered("view-script"))
Yii::app()->clientScript->registerScript("view-script","
$('.link').live('click',function(){
alert('test');
})
");
If I request for the controller for the first time, it works perfectly (alert 1 time) but if I request again for that same controller without refreshing my page and just using ajaxRequest, the alert will output twice if you click it (because it keeps on generating eventhough you already registered it once)
This is the same if you have CActiveForm inside the view with jquery functionality.. the corescript yiiactiveform will be called everytime you renderPartial.
To avoid including core scripts twice
If your scripts have already been included through an earlier request, use this to avoid including them again:
// For jQuery core, Yii switches between the human-readable and minified
// versions based on DEBUG status; so make sure to catch both of them
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
If you have views that are being rendered both independently and as HTML fragments to be included with AJAX, you can wrap this inside if (Yii::app()->request->isAjaxRequest) to cover all bases.
To avoid including jQuery scripts twice (JS solution)
There's also the possibility of preventing scripts from being included twice on the client side. This is not directly supported and slightly more cumbersome, but in practice it works fine and it does not require you to know on the server side what's going on at the client side (i.e. which scripts have been already included).
The idea is to get the HTML from the server and simply strip out the <script> tags with regular expression replace. The important point is you can detect if jQuery core scripts and plugins have already been loaded (because they create $ or properties on it) and do this conditionally:
function stripExistingScripts(html) {
var map = {
"jquery.js": "$",
"jquery.min.js": "$",
"jquery-ui.min.js": "$.ui",
"jquery.yiiactiveform.js": "$.fn.yiiactiveform",
"jquery.yiigridview.js": "$.fn.yiiGridView",
"jquery.ba-bbq.js": "$.bbq"
};
for (var scriptName in map) {
var target = map[scriptName];
if (isDefined(target)) {
var regexp = new RegExp('<script.*src=".*' +
scriptName.replace('.', '\\.') +
'".*</script>', 'i');
html = html.replace(regexp, '');
}
}
return html;
}
There's a map of filenames and objects that will have been defined if the corresponding script has already been included; pass your incoming HTML through this function and it will check for and remove <script> tags that correspond to previously loaded scripts.
The helper function isDefined is this:
function isDefined(path) {
var target = window;
var parts = path.split('.');
while(parts.length) {
var branch = parts.shift();
if (typeof target[branch] === 'undefined') {
return false;
}
target = target[branch];
}
return true;
}
To avoid attaching event handlers twice
You can simply use a Javascript object to remember if you have already attached the handler; if yes, do not attach it again. For example (view code):
Yii::app()->clientScript->registerScript("view-script","
window.myCustomState = window.myCustomState || {}; // initialize if not exists
if (!window.myCustomState.liveClickHandlerAttached) {
window.myCustomState.liveClickHandlerAttached = true;
$('.link').live('click',function(){
alert('test');
})
}
");
The cleanest way is to override beforeAction(), to avoid any duplicated core script:
class Controller extends CController {
protected function beforeAction($action) {
if( Yii::app()->request->isAjaxRequest ) {
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery-2.0.0.js'] = false;
Yii::app()->clientScript->scriptMap['anything.js'] = false;
}
return parent::beforeAction($action);
}
}
Note that you have to put the exact js file name, without the path.
To avoid including script files twice, try this extension: http://www.yiiframework.com/extension/nlsclientscript/
To avoid attaching event handlers twice, see Jons answer: https://stackoverflow.com/a/10188538/729324