为特定用户个人资料添加背景视频?

我目前正尝试将视频添加到特定的用户个人资料页面,以便我们所有的赞助者都能在他们的个人资料上拥有特定的背景视频。(在你大惊小怪之前,这只是一个循环动画,而不是一个完整的视频——看起来应该很不错,类似于 Steam 个人资料背景。)

以下 HTML 和 CSS 代码适用于所有用户——但这显然不是我们想要的:

// 这部分放在“Header”选项卡中

<video playsinline autoplay muted loop id="myVideo" poster="[INSERT LINK]">
	<source src="[INSERT LINK]" type="video/webm">
	<source src="[INSERT LINK]" type="video/mp4">
</video>
#myVideo {
  position: fixed;
  top: 63px;
  min-height: 1080px;
  margin-left: 50vw;
  transform: translate(-50%);
}

.user-content
{
    background: none;
}

.user-main .about.has-background .details {
    padding-bottom: 15px;
}
.user-main .about
{
    margin-bottom: 0px;
}
.user-content-wrapper
{
    background: rgba(var(--secondary-rgb), 0.8);
}

与使用 body.category-general 将图像添加到“general”类别中的页面不同,似乎没有为特定组或特定用户名的用户分配个人资料页面。我们对这方面了解不多,主要有 CSS 经验,而不是直接处理 HTML,因此不确定是否有简单/方便的方法可以实现我们想要的效果。

我们设想的最佳方法是根据用户组为用户个人资料添加类似的 slug,但我们不确定如何实现这一点以及如何仅在具有正确内容的页面上显示视频,并且我们也不打算仅使用此方法,如果存在其他更简单的方法。

例如,如果更容易,我们也愿意考虑逐个用户而不是逐个组进行此操作。

我们只是希望不要在每个页面上都硬编码视频,以便它仅在您查看特定用户时加载。

编辑: 我应该提到我们使用的是稳定分支,以防万一这会改变任何事情。

我们目前的方法是查看我们是否可以通过规范链接检测到我们是否在某个用户的页面上,如果是,则应用视频。因此,我们有以下内容:

<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>

但是,这似乎只在完全刷新时才有效 - 不知何故,从一页点击到另一页不会更新 --currUsername 属性,并且用户页面的背景色不是随机应用,而是如果最后一次按 F5 键是在用户页面上,则所有页面的背景色都是随机应用的,而如果最后一次按 F5 键是在非用户页面上,则任何页面都没有应用。

坦白说,我对 JavaScript 没有足够的经验,不知道为什么会这样——在我看来,在页面更改时,函数应该触发(它确实触发了),导致 pageURL 变量被更新,这应该会在加载页面时导致 --currUsername 属性被更新。但是,这只在完全刷新时发生,否则变量似乎不会改变。

有什么想法知道我在这里搞砸了什么吗?

这似乎是因为规范 URL 未更新,而“og:url”属性已更新。

唯一的问题是使用 var pageURL = document.querySelector("meta[property='og:url']").getAttribute("content"); 会在 meta 标签本身更新之前更新——也就是说,这段代码获取的是前一个页面的 URL,而不是当前页面的 URL。

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.

Plugin outlet locations theme component

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)

So, the one we want is above-user-profile

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.

and…

So far so good, but let’s dig deeper.

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

<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>

It looks like HTML - and the script tags are - but what’s inside them is treated as handlebars code.

That means that you can do something like this instead

<script type="text/x-handlebars" data-template-name="/connectors/above-user-profile/add-profile-videos">
  {{log this}}
</script>

and check the browser console. You’ll see this whenever the outlet is rendered; IE, you’re on a user page.

image

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.

Search · "above-user-profile" · GitHub

Let’s open that file. The first thing you see is this line

Look at the last bit of that line

args=(hash model=model)

You’ll see that Discourse passes model as an argument to the outlet. For all intents and purposes and to keep things simple, model = data

So, one of the arguments for our outlet is model, and that’s where the data we want is going to be. So, let’s go back to our snippet.

<script type="text/x-handlebars" data-template-name="/connectors/above-user-profile/add-profile-videos">
  {{log this}}
</script>

and let’s change it to this instead

<script type="text/x-handlebars" data-template-name="/connectors/above-user-profile/add-profile-videos">
-  {{log this}}
+  {{log args}}
</script>

Now we get this in the console.

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 :drum: … 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.

user groups logged 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.

So, let’s create one. We do it like this

<script type="text/discourse-plugin" version="0.8">
api.registerConnectorClass('OUTLET_NAME', 'SOME_NAME', {

});
</script>

OUTLET_NAME and SOME_NAME here should be the same as the ones we used above. So let’s change them

<script type="text/discourse-plugin" version="0.8">
api.registerConnectorClass('above-user-profile', 'add-profile-videos', {

});
</script>

This snippet goes in the common > header tab in your theme as well. So you should now have something that looks like this

<script type="text/x-handlebars" data-template-name="/connectors/above-user-profile/add-profile-videos">
  {{log args.model.groups}}
</script>

<script type="text/discourse-plugin" version="0.8">
  api.registerConnectorClass('above-user-profile', 'add-profile-videos', {

  });
</script>

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.

There are four methods wired up to it by default

actions allows you to define actions like so

api.registerConnectorClass("above-user-profile", "add-profile-videos", {
  actions: {
    myAction() {
      // do something
    }
  }
});

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…

api.registerConnectorClass("above-user-profile", "add-profile-videos", {
  setupComponent(args, component) {
    // do something
  }
});

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

api.registerConnectorClass("above-user-profile", "add-profile-videos", {
  teardownComponent(args, component) {
    // do something
  }
});

this fires when the outlet is going to be removed. So, it allows you to do any cleanup required, like remove event listeners and so on.

Ok, let’s go back to setupComponent

api.registerConnectorClass("above-user-profile", "add-profile-videos", {
  setupComponent(args, component) {
    // do something
  }
});

You can see that it has two things passed to it. First, there’s args and then there’s component

args here is the same stuff we looked at earlier. It’s the context data that Discourse passed to the outlet. So, if you do

api.registerConnectorClass("above-user-profile", "add-profile-videos", {
  setupComponent(args, component) {
    console.log(args.model.groups);
  }
});

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

  api.registerConnectorClass('above-user-profile', 'add-profile-videos', {
    setupComponent(args, component) {
      const inGroup = [...args.model.groups].filter(g => g.name === TARGET_GROUP)
      const showVideo = inGroup.length ? true : false;

      console.log(showVideo);
    }
  });

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

  const TARGET_GROUP = "staff"

  api.registerConnectorClass('above-user-profile', 'add-profile-videos', {
    setupComponent(args, component) {
      const inGroup = [...args.model.groups].filter(g => g.name === TARGET_GROUP)
      const showVideo = inGroup.length ? true : false;
-     console.log(showVideo);
+     component.setProperties({showVideo})
    }
  });

Now, if we head back to the template and do something like

{{log showVideo}}

and it will print the same result. So we now put that in a Handlebars condition and add your markup inside it like so

<script
  type="text/x-handlebars"
  data-template-name="/connectors/above-user-profile/add-profile-videos"
>
  {{#if showVideo}}
    <video playsinline autoplay muted loop id="myVideo" poster="[INSERT LINK]">
  	  <source src="[INSERT LINK]" type="video/webm">
  	  <source src="[INSERT LINK]" type="video/mp4">
    </video>
  {{/if}}
</script>

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

<script
  type="text/x-handlebars"
  data-template-name="/connectors/above-user-profile/add-profile-videos"
>
  {{#if showVideo}}
    <video playsinline autoplay muted loop id="myVideo" poster="[INSERT LINK]">
  	  <source src="[INSERT LINK]" type="video/webm">
  	  <source src="[INSERT LINK]" type="video/mp4">
    </video>
  {{/if}}
</script>

<script type="text/discourse-plugin" version="0.8">
  const TARGET_GROUP = "staff"

  api.registerConnectorClass('above-user-profile', 'add-profile-videos', {
    setupComponent(args, component) {
      const inGroup = [...args.model.groups].filter(g => g.name === TARGET_GROUP)
      const showVideo = inGroup.length ? true : false;
      component.setProperties({showVideo})
    }
  });
</script>

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.

  1. find the outlet name
  2. get the data
  3. process the data in a connector
  4. pass the properties back to the template
7 个赞

这非常深入,我下周有时间时一定会仔细看看,但 suffice to say 从快速浏览来看,它似乎比我目前的实现好得多(在每个页面上嵌入视频,并且只在用户个人资料中显示,我通过一个脚本实现的,该脚本会在用户的帐户名称是某个特定名称时向用户页面的 body 添加一个标签)。感谢您深入的解释,我迫不及待地想开始动手了!

2 个赞

好的,总的来说,这种方法效果很好,解释也很棒。非常感谢您的额外付出。

在用户基础上工作很简单——我们只需像这样检查给定的用户名:

      const isUser1 = args.model.username == "User1"
      component.setProperties({isUser1})

但是,我们在 CSS 方面遇到一个问题——我们希望仅针对这些用户更改用户页面的外观。

目前,我们通过与之前相同的代码来实现这一点:

<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>

这使我们能够为每个新用户简单地复制粘贴“User1”代码,但依赖于每次页面加载后 50 毫秒的延迟才能触发,这会显示给最终用户(如果删除,则因某种原因不起作用)。

是否有任何方法可以将此向 body 添加类的功能也集成到您提供的代码中,以便我们可以使用它来以不同于没有视频的页面样式化带有视频的页面?

而且,再次感谢您如此详尽的解释。

1 个赞