How do you pull in data from the DB for your theme components?

Anybody know if there is a guide or example for this anywhere please?

Let’s say for example I use a theme component to create a side column, how can I list the latest 20 publicly visible topics (or if it’s easier, from categories that I list in the query) in that side column/theme component?

1 Like

There’s a couple of ways to do this. The simplest is to use an ajax call to the endpoint in the rails API that serves the data you want to display. If you want the latest 20 topics, then you might want to try /latest.json.

The challenge is if you need to combine info from multiple endpoints you then wait on multiple calls to complete which can really slow performance down in the theme component.

4 Likes

Thanks for the reply Justin :slight_smile:

Is there an easy way to simply re-use feeds/data that Discourse already provides? (So that they honour that user’s settings too).

So for example in a side column we might have:

  • Latest 10 topics (feed from Latests page - but also honours muted categories)
  • Top topics this week (from /top)
  • Top topics this month
  • Top topics this year
  • Most active users this month (from /u?period=monthly)

This is actually fairly easy to do on other forum platforms and I really miss this with Discourse :sob:

Totally. Ajaxing the associated endpoints will respect the user’s current settings.

Hitting /latest.json will only show the latest topics that particular user can see.

GET from the same paths with .json appended to the URL and see what you find!

1 Like

Do you think that that would be more or less the same as just hitting the DB with whatever queries those endpoints do anyway? (Or would it use significantly more resources since it could be the same as having to load 5 additional pages - one for each endpoint).

Either way I’d love to experiment with this - are there any guides or tutorials that show you how to fetch data from an endpoint into a theme component? (Or would it be better/more efficient to make a plugin instead?)

I know how to create a theme component and a ‘dummy’ plugin, but haven’t found any guides that show you how to fetch data from the DB into them.

This guide shows how to do this with a specific tag, but you can replicate this approach with any endpoint really.

3 Likes