How to create a switch that changes the content of the page? - html

I have a drupal site 8 th I use Twig to customize my pages.
I created 2 blocks view :
drupal_view('message_activity_stream_timeline_public', 'block_1') }}
drupal_view('message_activity_stream_timeline_private', 'block_1') }}
On my homepage, I want to put a switch that goes from block_1 to block_2 and vice versa.
When the switch is on the position PUBLIC it must display the block drupal_view('message_activity_stream_timeline_public', 'block_1') }}.
When the switch is on the position PRIVÉ it must display the block drupal_view('message_activity_stream_timeline_private', 'block_1') }}.
It is not necessary to memorize the position.
How can I do this ?
Here is my page :
<div class="home-page-header-bottom">
<h5>Fil d’actualité <button type="button" class="btn btn-default btn-tooltip" data-toggle="tooltip" data-placement="bottom" title="Le fil d'actualité public affiche en temps réel toute l'activité publique qui se déroule sur le site. Le fil d'actualité privé affiche en temps réel uniquement l'activité publique des pages que vous aimez et l'activité privée liée à votre compte. Lorsque vous êtes connecté, vous pouvez basculer d'un fil d'actualité à l'autre."><i class="fas fa-info-circle fa-lg"></i></button></h5>
<div class="toggle-on-off">
<span class="toggle-on-off-public">PUBLIC</span>
<i class="fas fa-toggle-on fa-rotate-180 fa-3x"></i>
<span class="toggle-on-off-prive">PRIVÉ</span>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 home-page-footer">
<div class="col-md-12 timelines">
<div class="main-timeline">
{{ drupal_view('message_activity_stream_timeline_public', 'block_1') }}
{{ drupal_view('message_activity_stream_timeline_private', 'block_1') }}
</div>
</div>
</div>
Can you explain to me how to get the method with reloading the page and without reloading the page ?

You can set additional variables to send to a template using hook_preprocess_HOOK(), and then use that value within a twig conditional.
You'll also need to consider caching, otherwise Drupal's Dynamic Page Cache may store the rendered page fragment the first time it's needed and server it to all later users.
function MY_MODULE_hook_preprocess_ELEMENT(&$variables) {
// Add a variable to send to the template.
$variables['new_variable'] = TRUE;
// Add the appropriate cache contexts so that the template is re-rendered when needed.
$variables['#cache']['contexts'][] = 'session';
}

Related

Why does my page actualize on the anchor?

When i clicked on this button that i created 1 it makes me go there 2 and that is what i want. But it's what comes after that that is the unwanted result.
When i actualized the page, it will makes me go there again, i can understand why since the url will not change there since it was " [...]index.html#nom " and it will become the same after actualizing the page after i clicked on the button. But when i do something else, like clicking on the button " Accueil " the url will be this [index.html] but it will not make me go at the start of the page but there 3 when i want to be there 4.
So my question is this. Why when i actualize my page without clicking the button or clicking " Accueil" or clicking "Accueil" or the other "Accueil" in the three others pages [à propos ; Tarifs ; Portfolio] that is supposed to make me go at the start of the page " [...]index.html " it will make me go to " Voir mon portfolio " (seen in image 3).
I tried to understand why it doesn't work. But if i understand correctly.
If i use a <a href"#nom"> TEST . When a id="nom" was created before. When i clicked on the " TEST " it will makes me go at the same page, but at the id where it was located in the page. So in my case it works. But when i clicked on other things that's supposed to make me go at the start of the " Accueil" page. it just makes me go at another location.
I tried to use another ID with another anchor just to make the " Accueil " of the page accueil; à propos ; tarifs ; portfolio makes me go to the same anchor located at the start of the page so it will works out. But again, the url will change and it will be this " [...]index.html#haut ". So there go another problem. If i just actualize my page without the #haut it will make go at the location of image4 and if have already clicked on the button ( seen in image 1) then i need to click on the " Accueil" at the top... to go at the top of the page. So it kinds of lost his meaning.
While doing what i'm doing will makes it work. It doesn't work on some cases :
1 : If i'm going to the index page the first time, the url will be " [...] index.html " so it will makes me go at the location of image4.
2 : If i'm clicking on the button seen in image1, the url will change to " [...] index.html#nom ", and if i actualize the page it will makes me go there again. So if i want to go at the start of my page i need to go at the start by scrolling and clicking on Accueil, but it's not that great (since i don't need to click on accueil since i'm already at the start of the page).
I tried looking on the internet, but it only gave me explanation of the anchor and id and it doesn't seem like i did something wrong here so i don't really know.
<body>
<header>
<nav>
<img src="logo.png" alt="Logo Robbie Lens" id="haut">
<div>
Accueil
À propos
Tarif
Portfolio
</div>
</nav>
</header>
<main>
<section class="accueil-introduction">
<div>
<h1>Robbie Lens Photographie</h1>
<p>
Où <em>professionalisme</em> s’allie avec <em>passion</em>. Depuis
plus de 5 ans maintenant, j’exerce mon métier avec la passion
qui m’anime : capturer l’essence de chaque instant.
</p>
UN PROJET ? ÉCRIVEZ-MOI
</div>
<img src="robbie-lens.png" alt="Portrait avec effet de la photographe Robbie Lens" >
</section>
<section class="accueil-photos">
<h2>Mon dernier projet</h2>
<div>
<img src="element-1.png" alt="Twelve apostles - Australie" >
<img src="element-2.png" alt="Wai-O-Tapu - Nouvelle-Zélande" >
<img src="element-3.png" alt="Parc National d’Abel Tasman - Nouvelle-Zélande" >
</div>
<div>
<img src="element-4.png" alt="Lac Rotorua - Nouvelle-Zélande" >
<img src="element-5.png" alt="Milford Sound - Nouvelle-Zélande" >
<img src="element-6.png" alt="Lac Wanaka - Nouvelle-Zélande" >
</div>
<div>
VOIR MON PORTFOLIO
</div>
</section>
<section>
<h2 class="tortue" >Parlons de votre projet</h2>
<form method="get" action="#">
<div class="form-nom-email">
<div class="form-column">
<label for="nom">nom</label>
<input type="text" name="nom" id="nom" required autofocus>
<label for="email">e-mail</label>
<input type="email" name="email" id="email" required >
</div>
<div class="form-column">
<label for="message">Votre message</label><br>
<textarea name="message" id="message" cols="40" rows="4"></textarea required>
<input type="submit" value="ENVOYER" class="cta">
</div>
</div>
</form>
</section>
</main>
<footer>
<img src="logo.png" alt="Logo Robbie Lens" >
<div>
<a target="_blank" href="https://twitter.com/" class="lien-icone">
<img src="twitter.png" alt="Logo Twitter" >
</a>
<a target="_blank" href="https://www.instagram.com/" class="lien-icone">
<img src="instagram.png" alt="Logo Instagram" >
</a>
</div>
</footer>
</body>
Thanks for your answer and if the question was already made and answered i'm sorry.
Have a nice day.

How to create a copy text link?

I created a code and I want the visitor to be able to copy the BTC address <small type="text" id="copy-to-clipboard">{{ group.field_groupe_donation.value }}</small> by clicking on the fontawesome icon <button class="btn btn-default btn-xs" onclick="copyText()"><i class="fas fa-copy"></i></button>.
How to do this ?
(function($) {
function copyText() {
var text = document.getElementById("copy-to-clipboard");
text.select();
document.execCommand("copy");
alert("Copied the text: " + text.value);
}
})(jQuery);
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="message-donation text-justify">
<div>Si le contenu de ce groupe vous plait, vous pouvez faire un don à son l'auteur en Bitcoin (BTC).</div>
<div class="h3"><i class="fab fa-bitcoin fa-lg btc"></i> Adresse BTC :</div>
{{ content.field_groupe_donation }}
<small type="text" id="copy-to-clipboard">{{ group.field_groupe_donation.value }}</small>
<button class="btn btn-default btn-xs" onclick="copyText()"><i class="fas fa-copy"></i></button>
<div class="mt-3 text-center">
<b>Comment ça marche ?</b>
</div>
</div>
Here is the result :
It does not work.
After modifying your code, I propose to create the "copyText" function in this way.
function copyText() {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($("#copy-to-clipboard").text()).select();
document.execCommand("copy");
$temp.remove();
alert('Copied');
}
The instruction document.execCommand("copy"); allows you to copy all the elements of the DOM you have selected using the .select() function.
You can use the clipboard API for this. Please note that this requires your site to run in a secure context (https or localhost).
Example:
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('bar').addEventListener('click', () => {
if (window.isSecureContext && 'clipboard' in navigator) {
navigator.clipboard.writeText(document.getElementById('foo').textContent);
} else {
console.error(`Clipboard API requires secure context or your browser doesn't support clipboard API`);
}
})
})
<small id="foo">This text should be in your clipboard after clicking the copy button</small>
<br />
<button id="bar" type="button">copy</button>
<br />
<textarea placeholder="try pasting here after clicking copy button" cols="60" rows="3"></textarea>
As with most things, in 2020 you want to be using the browser API and not jQuery.

Reduce select size: size adjust to filter options

I have a simple problem I do not know how to manage
I have a simple select that receive a full list of option
I use JS to filter the shown option based on another select (source: http://jsfiddle.net/pz9cjmLg/5/)
when I click on the right arrow of the select, list is shown
first option is empty
but I would like to adjust the size of the list to the size of options shown and not the the total size of the list (see picture below)
I try to use size="3" (for example) but it is not what I need
html
<form id="form_reallocation" method="POST" class="post-form">
{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlSelect1"><strong>{% trans 'Patient code number :' %}</strong></label>
<select required name="patients" class="form-control" id="patients" data-patient-url="{% url 'randomization:patient' %}">
<option value=""></option>
{% for patient in patients %}
<option value="{{ patient.ran_log_sit }}/{{ patient.ran_num }}">{{ patient.ran_num }}</option>
{% endfor %}
</select>
</div>
<br><br>
<button id="reallocate" type="submit" class="btn btn-primary">{% trans 'Reallocate' %}</button>
</form>
JS
sel.on('change', function () {
selected_site = this.value;
var value = site_abbreviation(parseInt(selected_site));
var options = $("#patients option");
// on commence par masquer toutes les options
// options.hide();
$("#patients option[value]").filter(function() {
return +$(this).val() != "";
}).hide();
// on affiches les options correspondant au site sélectionné
var op = options.filter(function () {
// return value == $(this).val().slice(4,6); // on retourne les options dont la valeur (numéro patient) contient le code lettre du site
return value == $(this).val().slice(0,2); // gestion des patients pré-inclus dans un site et randomisé dans un autre centre
}).show();
$("#patients").val(op.eq(0).val());
// $("#patients")[0].selectedIndex = 0;
$("#patients option:selected").prop("selected", false);
$("#patients option:first").attr('selected','selected').change();
})
Could you disable the second select box so that it can only be selected once the first dropdown has been chosen and isnt null?
so initialise the second select with "disabled" then use
$(".CompName").removeAttr("disabled")
With the CompType onChange event?

How to format the address in TWIG?

I have a Drupal site and I want to format the address in TWIG.
How do I delete spaces before and after the address?
How to replace the tags "<br>" by " - " ?
Here is the TWIG code :
<strong>Adresse postale :</strong> {{ store.address }}
Here is the rendering :
<pre class="text-left"><strong>Raison sociale :</strong> Poupette & Cacahuète.
<strong>Adresse postale :</strong>
<div class="field field--name-address field--type-address field--label-hidden field--item"><p class="address" translate="no"><span class="address-line1">rue du vermont</span><br>
<span class="postal-code">14600</span> <span class="locality">Honfleur</span><br>
<span class="country">France</span></p></div>
<strong>Téléphone :</strong> .
<strong>Adresse électronique :</strong> poupette.cacahuete14#gmail.com
<strong>Boutique :</strong> https://www.s1biose.com/fr/boutique/poupette-cacahuete
Immatriculé au de sous le numéro .
</pre>
If you would like complete control over the render of this, you can access the individual address 'pieces' by using store.address.my_value. So for instance, your address as you described it in a comment would look like:
<span class="my-class">
{{ store.address.address_line1 }} - {{ store.address.postal_code }} {{ store.address.locality }} - {{ store.address.country }}
</span>
If this is the way you always want this to appear, consider adding a theme override for the address-plain.html.twig template to render this as you would like consistently. You can start by copying the module's template from docroot/modules/contrib/address/templates/address-plain.html.twig and altering it within your theme to be as you like.
You can use replace and trim functions like this:
{{ store.address|trim|replace({'<br>': '-'})|raw }}

Extra indentation for <strong> and <a>tags?

Hello Stack Overflow community,
I have coded a list:
<h2 class="top-heading-big" style="text-align: center;">Déroulement de la Prestation</h2>
<ul style="line-height: 160%;">
<li class="presta"><a target="_blank" class="retour" href=/pages/contact title="Envoyer un email à Pascal pour recevoir un Audit" style="text-decoration: underline; color:#1990C6;">Prise de contact</a> avec votre besoin succintement décrit</li><br>
<li class="presta">Audit Vidéo de 10 min, Gratuit et Sans Engagement </li><br>
<li class="presta">Ajustement & Établissement du Devis</li><br>
<li class="presta">Réception du Paiement</li><br>
<li class="presta">Prestation livrée dans les meilleurs délais</li><br>
<li class="presta">Compte-Rendu en vidéo de 10 min, et réception du feedback client avec témoignage</li><br>
<li class="presta"><strong>Consulting Personnalisé Offert</strong> pour aller plus loin</li><br>
</ul>
<br>
It looks like the indentation is not regular among the different lines of my list.
In particular, the first and last lines have an extra indentation.
So I immediately thought, this is because of the and tags that appear right at the beginning of each lines.
I had none idea of this, could you confirm?
And if this a well-known fact, what would be the best solution to have an aquel indentation for each line?
I know I could put a new class for the first and last element, and then play with CSS to adapt this extra indentation, but I'm pretty sure there is something better.
PS: I'm using Google Chrome last version
Any help would be greatly appreciated on this matter :)
Sincerely, Pascal
URL: https://www.pascaldegut.com/pages/prestation-webdesign?variant=16668787376246
Just give it a try: remove the whitespaces in the first and last li content right at the beginning, please.
I've looked at your generated HTML Code of the given URL above. It's not the exact semantic. It's obviously not a valid html semantic. Change your code from:
<ul style="line-height: 160%;">
<li class="presta">
<a target="_blank" class="retour" href="/pages/contact" title="Envoyer un email à Pascal pour recevoir un Audit" style="text-decoration: underline; color:#1990C6;">Prise de contact</a> avec votre besoin succintement décrit</li>
<br>
<li class="presta">Audit Vidéo de 10 min, Gratuit et Sans Engagement </li>
<br>
<li class="presta">Ajustement & Établissement du Devis</li>
<br>
<li class="presta">Réception du Paiement</li>
<br>
<li class="presta">Prestation livrée dans les meilleurs délais</li>
<br>
<li class="presta">Compte-Rendu en vidéo de 10 min, et réception du feedback client avec témoignage</li>
<br>
<li class="presta">
<strong>Consulting Personnalisé Offert</strong> pour aller plus loin</li>
<br>
</ul>
to:
<ul style="line-height: 160%;">
<li class="presta"><a target="_blank" class="retour" href="/pages/contact" title="Envoyer un email à Pascal pour recevoir un Audit" style="text-decoration: underline; color:#1990C6;">Prise de contact</a> avec votre besoin succintement décrit</li>
<li class="presta">Audit Vidéo de 10 min, Gratuit et Sans Engagement </li>
<li class="presta">Ajustement & Établissement du Devis</li>
<li class="presta">Réception du Paiement</li>
<li class="presta">Prestation livrée dans les meilleurs délais</li>
<li class="presta">Compte-Rendu en vidéo de 10 min, et réception du feedback client avec témoignage</li>
<li class="presta"><strong>Consulting Personnalisé Offert</strong> pour aller plus loin</li>
</ul>
I've also removed the <br>s between the <li> elements. For the spacing purpose you have to define a margin to the <li> elements. To create a valid mark up you have to remove <br> as direct childs of <ul>. If you really need this sort of break you can use it like that: <li>some content<br></li>
Anyway, I recommend a margin-bottom for this behaviour.