Sto attualmente tentando di aggiungere un video alle pagine del profilo di utenti specifici, in modo che tutti i nostri mecenati abbiano un certo video di sfondo sul loro profilo. (Prima che vi agitiate troppo, sarebbe solo un’animazione in loop, non un video completo - dovrebbe avere un bell’aspetto, simile agli sfondi dei profili di Steam.)
Il seguente codice HTML e CSS funziona per tutti gli utenti, ma ovviamente non è quello che stiamo cercando:
// Questo va nella scheda "Header"
<video playsinline autoplay muted loop id="myVideo" poster="[INSERISCI LINK]">
<source src="[INSERISCI LINK]" type="video/webm">
<source src="[INSERISCI LINK]" type="video/mp4">
</video>
A differenza dell’uso di body.category-general per aggiungere un’immagine solo alle pagine della categoria “generale”, non sembrano esserci slug specifici assegnati alle pagine del profilo degli utenti di un gruppo specifico o di un nome utente specifico. Siamo abbastanza nuovi a questo e abbiamo principalmente esperienza con il CSS piuttosto che con lavori diretti sull’HTML, e quindi non siamo sicuri se esista un modo semplice e conveniente per far funzionare le cose come vorremmo.
Immaginiamo che l’approccio migliore sarebbe aggiungere uno slug simile per i profili utente basato sul loro gruppo, ma non siamo sicuri di come farlo accadere e di come far apparire il video solo nelle pagine con il contenuto corretto, e inoltre non siamo impegnati a utilizzare specificamente questo approccio se esiste un altro metodo più semplice.
Ad esempio, saremmo anche aperti all’idea di farlo su base per utente anziché per gruppo, se ciò fosse in qualche modo più semplice.
Preferiremmo semplicemente non dover codificare il video su ogni pagina, in modo che venga caricato solo quando ci si trova sugli utenti specifici in questione.
Modifica: Probabilmente dovrei notare che siamo sulla branch stabile, nel caso in cui ciò cambi qualcosa.
Il nostro approccio attuale è verificare se riusciamo semplicemente a rilevare che ci troviamo sulla pagina di un determinato utente tramite il link canonico e, in tal caso, applicare il video. Pertanto, abbiamo quanto segue:
<script type="text/discourse-plugin" version="0.8">
api.onPageChange(() => {
determineUser();
});
function determineUser() {
var pageURL = document.querySelector("link[rel='canonical']").getAttribute("href");
var isUserPage = pageURL.includes("https://www.fortressoflies.com/u/");
document.documentElement.style.setProperty('--currUsername', pageURL);
if(isUserPage)
{
document.documentElement.style.setProperty('--lastUsername', pageURL);
$('body').css('background-color', '#'+(Math.random()*0xFFFFFF<<0).toString(16));
}
}
</script>
Tuttavia, questo sembra funzionare solo con un aggiornamento completo - per qualche motivo, navigare da una pagina all’altra non aggiorna la proprietà --currUsername e, invece di applicare uno sfondo di colore casuale alle pagine utente, applica uno sfondo di colore casuale a tutte le pagine se F5 è stato premuto l’ultima volta su una pagina utente, mentre non applica nulla a nessuna pagina se F5 è stato premuto l’ultima volta su una pagina non utente.
Francamente, non ho abbastanza esperienza con JavaScript per sapere perché ciò accada: mi sembra che, al cambio di pagina, la funzione dovrebbe essere eseguita (cosa che fa), facendo aggiornare la variabile pageURL, e questo dovrebbe causare l’aggiornamento della proprietà --currUsername al caricamento di una pagina. Tuttavia, ciò si verifica solo con un aggiornamento completo, altrimenti le variabili non sembrano cambiare.
Sembra che ciò sia dovuto al fatto che l’URL canonico non viene aggiornato, mentre la proprietà “og:url” sì.
L’unico problema è che l’uso di var pageURL = document.querySelector("meta[property='og:url']").getAttribute("content"); si aggiorna prima che il tag meta stesso venga aggiornato, ovvero questo codice mi fornisce l’URL della pagina precedente, non quella corrente.
If you want to add content to a specific page, your best option is a plugin-outlet. In a nutshell, plugin-outlets are spaces reserved in Discourse templates that you can use to add new content.
The first thing you’ll need to find out is if a plugin-outlet exists on the page you want to target. There’s a theme component that you can install that helps you with that.
Once you install that component, toggle it, head over to the page you want to target and check what you have to work with. In your case, such a plugin-outlet exists (highlighted in green)
Suppose that it didn’t exist… what then? The best option, in that case, is to ask for it to be added or send a PR to add it to core. It will get accepted most of the time if your use-case makes sense.
Anyway, as I said, it already exists in this case. So, let’s see how you can add markup to it. You won’t need the component above for the rest of this, so you can disable it now since you already have the name of the plugin outlet.
All you need to do is add something like this in the header tab of your theme.
<script type="text/x-handlebars" data-template-name="/connectors/OUTLET_NAME/SOME_NAME">
Your markup goes here...
</script>
You need to change OUTLET_NAME to the name of the outlet you want to target. Then change SOME_NAME to the name you want to give this customization. The name can be anything, but try to be descriptive if you can. It’s a good practice. So, we end up with this.
<script type="text/x-handlebars" data-template-name="/connectors/above-user-profile/add-profile-videos">
Your markup goes here...like
<h1>Hello World!!</h1>
</script>
Let’s try that and see what happens… remember, the snippet above goes in your theme’s common > header tab.
You don’t want your videos to show on every profile, and you want them to only show based on some condition. So, how do you do that? Well, you’ll need two things, some data to consume and a bit of Javascript.
Let’s find the data. Remember when I said plugin-outlets are reserved spaces? Well, what’s the point of having them without context? That’s why Discourse passes the relevant bits of context to each plugin outlet… but first, let’s take a step back. When you add this
and check the browser console. You’ll see this whenever the outlet is rendered; IE, you’re on a user page.
Now, is any of this stuff helpful? Yes… but not at the moment. We’ll come back to this. Let’s take another step back and see how Discourse passes the context to the outlet. If you search for the outlet name on Github - or locally - you’ll get this.
You can browse through that data and see if it has what you need. It should since it contains all the data about the user used in other elements on that page. It’s the “model” for the user page for that particular user.
One of the properties available there is… drumroll … the groups the user belongs to.
So, if you do
{{log args.model.groups}}
you’ll get all the groups the user belongs to in the console.
Alright, now we have the data we need, so the only thing left is to add some condition(s) based on that.
You might be tempted to think that we can do that in the same snippet, but, unfortunately, we can’t. Handlebars is a templating language. It has very, very basic support for logic - nothing beyond simple true/false conditions and loops. You can’t do comparisons and other stuff like that.
So where exactly can you do that? In a connector class, sounds fancy… I know.
In a nutshell, a connector class is essentially a bit of Javascript attached to the outlet. It’s a lot more nuanced than that, but that’s all you really need to know for now.
Inside our connector class, we can do some work… but… we need to be mindful that it’s not just like any javaScript file. For lack of a better description… think of it as an Ember component on a diet. Expanding on this is a bit outside the scope here, so let’s move on.
You can then call that action from within the outlet, like when a button is pressed. We won’t be needing this one here, so let’s move on.
api.registerConnectorClass("above-user-profile", "add-profile-videos", {
shouldRender(args, component) {
// return true or false here
}
});
We also won’t be using this one since the outlet only renders on profile pages, and we don’t have any other requirements for now. However, you can use this to add any conditions you want to test before the outlet is rendered. For example, the trust-level of the current user or stuff like that. Moving on…
This is the one we want to focus on. Whatever javaScript conditions or variables you want to set go here. Before we dig deeper into that one, let’s cover the last method first for completeness’ sake
you’ll see the same information in the browser console that we saw before. The groups that the profile owner belongs to. This is where the fun begins, you now have the data, and you have the correct hook. So you can do whatever you want here. So, if I want the video to only show on the profiles of members that belong to a certain group, I can do this
If you try this on a profile page that belongs to a user in the staff group, it will print true in the console. So, now the only thing we have left to do is to pass that to the outlet template. Here’s how you can do that.
component passed to setupComponent here is shared between the connector and the outlet. You can pass things to the outlet by setting them as properties on the component like so
then check a profile page for a staff user. You’ll see that it loads the video.
Once you navigate away from the staff member’s profile, the video will go away. The video won’t show on profiles for users who are not in the staff group.
So, let’s put all of this together. This is the same stuff from above.
Here’s the CSS I used. common > css tab
#myVideo {
position: fixed;
top: var(--header-offset);
min-height: 100vh;
left: 0;
z-index: -1;
}
.user-content {
background: none;
}
.user-main {
padding: 0.5em;
background: rgba(var(--secondary-rgb), 0.8);
}
// if you want it on mobile too
.mobile-view {
body[class*="user-"] {
background: none;
.user-main,
.user-content {
padding: 0.5em;
background: rgba(var(--secondary-rgb), 0.8);
}
}
}
HTML / javaScript / Handlebars. This goes in the common > header tab of your theme
Change TARGET_GROUP to the name of the group you want to target and add the src attributes for your videos.
This post was on the longer side… don’t be deterred by that. Once you grasp the concept, everything we did above can be done in less than 3-5 minutes.
The nice thing here is that all the stuff we talked about is pretty much the same for any plugin outlet. The only thing that changes is the name. So, this applies to any plugin-outlet modifications you want to do in the future.
È incredibilmente approfondito e mi assicurerò di esaminarlo quando avrò un po’ di tempo la prossima settimana, ma basti dire che da una scorsa sembra molto meglio della mia attuale implementazione (incorporare il video su ogni singola pagina e mostrarlo solo sul profilo utente, cosa che ho realizzato con uno script che aggiunge un tag al corpo della pagina di un utente se il nome del suo account è una certa cosa). Grazie per la spiegazione approfondita, non vedo l’ora di metterci mano!
Tuttavia, incontriamo un problema con il nostro CSS: desideriamo apportare alcune modifiche all’aspetto della pagina utente solo per questi utenti.
Al momento, lo stiamo realizzando tramite lo stesso codice di prima:
<script type="text/discourse-plugin" version="0.8">
api.onPageChange(() =>{
window.onload = determineUser();
});
async function determineUser() {
await sleep(50);
var pageURL = document.querySelector("meta[property='og:url']").getAttribute("content");
var isUserPage = pageURL.includes("https://www.siteurl.com/u/");
var isUser1 = pageURL.includes("u/User1/");
document.body.className = document.body.className.replace(" user-page-animated","");
if(isUserPage)
{
if(isUser1)
{
document.body.className += ' user-page-animated';
}
}
}
function sleep(ms)
{
return new Promise(resolve => setTimeout(resolve, ms));
}
</script>
Questo ci permette di copiare e incollare semplicemente il codice “User1” per ogni nuovo utente, ma si basa su un ritardo di 50 ms dopo ogni caricamento della pagina prima di attivarsi, il che è visibile all’utente finale (e, se rimosso, non funziona per qualche motivo).
C’è un modo per agganciare anche questa aggiunta di una classe al body al codice che hai fornito, in modo da poterla utilizzare per stilizzare le pagine con video in modo diverso da quelle senza?