How to make a theme component for TL-based banner

This will depend on your desired goal. If there’s no problem with using CSS, then yeah, this is pretty straightforward.

The reason why the code you added in the header doesn’t work is because trust is not defined. First you need to define what trust is. You can do it with something like this:

const container = Discourse.__container__,
  controller = container.lookup("controller:application"),
  trust = controller.get("currentUser.trust_level");

In the context of the code you tried it would look like this:

<script type="text/discourse-plugin" version="0.8.18">
const container = Discourse.__container__,
  controller = container.lookup("controller:application"),
  trust = controller.get("currentUser.trust_level");

api.onPageChange(() => {
  if (Discourse.User.current() && trust == "0") {
    $("#banner-content div:nth-child(1)").addClass("TL-selected");
  }
});
</script>

Now this works, but is not ideal. onPageChange fires on everypage change and if you do that and navigate a few pages on your site then check #banner-content div:nth-child(1) it would look like this:

<div id="banner-content">
  <div class="TL-selected TL-selected TL-selected TL-selected TL-selected TL-selected TL-selected TL-selected TL-selected TL-selected TL-selected TL-selected"></div>
</div>

Because the class would get added with every page change.

Perhaps a better way is to add the current user’s trust level to the <html> tag. This is of course only one option as this component can be as simple or as complex as you need it to be. However, let’s keep things simple for now.

So you can use something like this:

<script type="text/discourse-plugin" version="0.8.18">
$(document).ready(function() {
  const container = Discourse.__container__,
    controller = container.lookup("controller:application"),
    trust = controller.get("currentUser.trust_level"),
    trustClass = "trust-level-" + trust;

  $("html").addClass(trustClass);
});
</script>

All this does is find out what the trust_level is like I mentioned before, then constructs a CSS class name and adds it to the <body> tag. I wrapped it around in document ready for good measure.

This runs only once on initial page load. The result looks like this:

Capture

So, now you have a class in place that you can target with CSS. For a basic example you can do something like this:

.tl1-content,
.tl2-content,
.tl1-content,
.tl4-content {
  display: none;
}

.trust-level-1 .tl1-content,
.trust-level-2 .tl2-content,
.trust-level-3 .tl3-content,
.trust-level-4 .tl4-content {
  display: block;
}
8 Likes