Navigate back to the homepage

Create A Searchable Content Directory With CloudPages

Jason Hanshaw
May 10th, 2020 · 3 min read

Whether you’re struggling with a chaotic folder structure, or just generally having a hard time finding what you want, having a convenient way of searching your Content Builder assets can save quite a lot of time and frustration. Using the REST API and Code Resources, we can create a solution that allows us to efficiently view, or modify, any Content Builder asset within a searchable index.

Setup:

Before getting started, we’ll need to setup a data extension that will serve as our asset table that we can filter and search on. Let’s call this data extension Content Reference Directory Lookup. Our new data extension should have the following columns for this example:

  • contentID (Primary Key)
  • name
  • content
  • catID
  • custKey

We’ll also need to create an installed package so that we can access Content Builder assets programmatically with the REST API. If you are unsure of how to create and install a package in your SFMC account, please refer to the following documentation for more information:

Create and Install Packages

Create JSON Code Resource:

Next, we’ll create a JSON Code Resource that will serve our Content Directory CloudPage with asset data. To enable this functionality, we’ll simply need to initialize our data extension from the previous step and output the JSON response. This ensures that the asset data we store in our asset table will be updated and served to our CloudPage when a user visists or refreshes the directory.

1<script runat=server>
2Platform.Load("Core", "1");
3// User Filter For Limited Response Size Or Pagination
4var data = DataExtension.Init("Content Reference Directory Lookup").Rows.Retrieve(filter);
5Write(Stringify(data));
6</script>

Now that we’ve got our data extension created, and JSON Code Resource configured to serve our asset data, we can move on to implementing our CloudPage solution.

Configuring The CloudPage Directory:

The CloudPage that will execute on the data setup from the previous step can be broken down into three distinct pieces:

  1. Script to retrieve asset data and update our content database.
  2. VueJS function to retrieve our JSON Code Resource and allow a user to search for assets by name whilst sorting the result set.
  3. HTML/CSS to output Content Builder asset information.

Using SSJS To Update Data Extension

In order to generate the list of assets, and its associated data, within our solution we’ll need to retrieve them from the REST API. First, we’ll make a call to retrieve our API access token and then we’ll make a second call to retrieve our assets. For this example, we’ll only retireve HTML Content Blocks (assetType 197), but the below solution can be extended to allow all asset types or only those defined by a user.

We’ll then setup our script to parse the response from our call to retrieve the assets in order to extract the relevant data we need. After that, we’ll upsert the data to our asset table so that our JSON Code Resource can access our updated content.

Note: When dealing with a large volume of Content Builder assets, it is important to paginate your API requests and asset retrieval in order to improve performance and decrease the likelihood of an error. This is not included in the example below, but can be added with modest changes. Also, it is advisable that you execute the following script in an activity that runs hourly, rather than on page load. This implementation is for demonstration only.

1<script runat="server">
2Platform.Load("Core", "1");
3var url = 'https://YOUR-AUTH-ENDPOINT.com/v2/token';
4var contentType = 'application/json';
5var authPayload = {
6 "grant_type": "client_credentials",
7 "client_id": "your client id",
8 "client_secret": "your client secret",
9 "account_id": "your mid"
10};
11authPayload = Platform.Function.Stringify(request);
12var result = HTTP.Post(url, contentType, authPayload);
13var aRes = Platform.Function.ParseJSON(result.Response.toString());
14var auth = aRes.access_token;
15var assetURL = 'https://YOUR-REST-ENDPOINT.com/asset/v1/content/assets/query';
16var contentType = 'application/json';
17var contentPayload = {
18 "query": {
19 "property": "assetType.id",
20 "simpleOperator": "equals",
21 "valueType": "int",
22 "value": 197
23 },
24 "page": {
25 "pageSize": 1000
26 }
27};
28contentPayload = Platform.Function.Stringify(contentPayload);
29var headerNames = ["Authorization"];
30var headerValues = ["Bearer " + auth];
31var req = HTTP.Post(assetURL, contentType, contentPayload, headerNames, headerValues);
32var res = req.Response.toString();
33var json = Platform.Function.ParseJSON(res);
34var items = json.items;
35for (var i = 0; i < items.length; ++i) {
36 var itr = items[i];
37 var contentName = itr["name"];
38 var content = itr["content"];
39 var contentID = itr["id"];
40 var custKey = itr["customerKey"];
41 var catID = itr["category"]["id"];
42 Platform.Function.UpsertData("Content Reference Directory Lookup", ["contentID"], [contentID], ["name", "content", "catID", "custKey"], [contentName, content, catID, custKey]);
43}
44</script>

VueJS Function For Retrieving And Searching Data

Now that we’ve updated our data extension with the most recent assets, and have our Code Resource in place to output it, we’ll retrieve the data and bind it for filtering and display on our CloudPage.

First we’ll create a new Vue instance and specify the DOM element that we want it to control (an element with an id of app in this instance). Then, after the instance has been mounted, we’ll make an AJAX request in order to retrieve the data from our Code Resource. We’ll use computed properties in order to provide our functionality for filtering, and sorting, our assets by name as our user enters their search input.

1<script>
2new Vue({
3 el: "#app",
4 data: {
5 Data: [],
6 filterValue: "",
7 sortAsc: true,
8 },
9 mounted: function () {
10 var self = this;
11 // Get Code Resource To Retrieve Content Block Data
12 $.ajax({
13 url: "YOUR-JSON-CODE-RESOURCE-URL",
14 method: "GET",
15 success: function (data) {
16 self.Data = data;
17 },
18 error: function (error) {
19 console.log(error);
20 },
21 });
22 },
23 computed: {
24 filteredAndSortedData() {
25 // Apply Filter From User Input
26 let result = this.Data;
27 if (this.filterValue) {
28 result = result.filter((item) =>
29 item.name.toLowerCase().includes(this.filterValue.toLowerCase())
30 );
31 }
32 // Sort The Filtered Response
33 let ascDesc = this.sortAsc ? 1 : -1;
34 return result.sort((a, b) => ascDesc * a.name.localeCompare(b.name));
35 },
36 },
37});
38</script>

The last piece of this implementation will be to implement the markup and styles portion of the CloudPage that will show our filtered lists of assets and their properties.

Adding Markup and Styles

In order to iterate over our filtered asset JSON and display the relevant information to the user, we’ll need to use the v-for directive to map our array to elements in order to retrieve each instance of an asset. Notice that we are executing our functionality within the DOM element we defined in our Vue instance initialization and that we are accessing each element property within our v-for directive using the alias n. Using this approach, we’re able to a content block’s name, id, raw HTML and to generate a preview of its contents.

1<div id="app">
2 <div class="container">
3 <div class="col-sm-12">
4 <p>
5 Start Typing The Content Name To Filter Blocks:
6 </p>
7 <input type="text" v-model="filterValue" placeholder="Content Block Name">
8 </div>
9 </div>
10 <div class="container">
11 <div v-for="n in filteredAndSortedData" class="col-sm-12">
12 <div class="col-sm-12">
13 <div class="col-xs-3 left" >
14 <div class="padding">
15 <h6 class="reference_title"> {{n.name}}</h6>
16 <p>ID: {{n.contentID}}</p>
17 <textarea readonly onfocus="this.select();" onmouseup="return false;">{{n.content}}</textarea>
18 </div>
19 </div>
20 <div class="col-xs-9 right">
21 <div class="content_render" v-html="n.content">{{n.content}}</div>
22 </div>
23 </div>
24 </div>
25 </div>
26</div>

The only thing left to do is add in our styles and include the relevant external libraries related to our UI and VueJS functionality.

1@media only screen and (max-width: 480px) {
2.content_render {
3 width: 100%;
4 height: auto !important;
5}
6
7a.button {
8 -webkit-appearance: button;
9 -moz-appearance: button;
10 appearance: button;
11 text-decoration: none;
12 color: initial;
13 background: #154172;
14 color: white;
15 border-radius: 5px;
16 padding: 10px 20px;
17}
18
19body {
20 background: #fafafa;
21 padding-bottom: 20px;
22}
23
24h6 {
25 word-break: break-all;
26}
27
28header {
29 background: #3949d8;
30 color: rgb(255,255,255);
31}
32
33input {
34 min-width: 350px;
35 margin: 0 auto;
36 padding-left: 10px;
37}
38
39input {
40 width: 100%;
41}
42
43textarea {
44 height: 140px;
45 font-size: 12px;
46}
47}
48
49.buttons {
50 background: #e3e3e3;
51 margin-top: 0;
52 padding: 20px 0 20px 0;
53 max-width: 956px;
54}
55
56.center {
57 margin: 0 auto;
58 text-align: center;
59}
60
61.col-sm-12 {
62 padding-top: 30px;
63 text-align: center;
64}
65
66.col-xs-9, .col-xs-3 {
67 padding-top: 20px;
68 display: inline-block;
69 height: 325px;
70 vertical-align: middle;
71}
72
73.content_render {
74 width: 100%;
75}
76
77.left {
78 background: #e3e3e3;
79 color: #222;
80 width: 250px;
81}
82
83.logo {
84 margin: 0 auto;
85 display: block;
86 padding: 20px 0 20px 0;
87}
88
89.padding {
90 padding: 15px;
91}
92
93.right {
94 padding-left: 50px;
95 border: 1px solid #e3e3e3;
96 width: 700px;
97 overflow: auto;
98}
99
100.right, .left {
101 display: block !important;
102 width: 100%;
103}
104
105.row {
106 margin-top: 20px;
107 margin-bottom: 20px;
108}
109
110.text_center {
111 padding-top: 10px;
112}

Content_Reference_Directory

Conclusion:

Now we are able to provide users with an easily extendable, and searchable, solution for accessing their Content Builder assets. This solution could be modified to provide functionality for performing CRUD operations on assets or be integrated to work with external content management systems to provide a more holistic view of the asset model.

In addition to this blog post, you can find the code for this example in this github repository.

More articles from InvokeCreate

Search A Data Extension From Sales Cloud

Create a lightning component to search a Send Logging data extension in Marketing Cloud.

February 14th, 2020 · 7 min read

Pull Assets To Local Storage With Python

Export assets from Content Builder to local storage using the REST API

January 5th, 2020 · 4 min read
© 2020 InvokeCreate
Link to $https://github.com/invokecreate/Link to $https://www.linkedin.com/in/jason-hanshaw-developer/Link to $https://salesforce.stackexchange.com/users/50722/jason-hanshaw