How to pass multiple files in template_file block

I am trying to inject bunch of files into template_file using for_each . but I am getting exception. Main reason to go with this approach is to update the json files dynamically with the var.

resource "datadog_monitor_json" "monitor_json" {
         monitor = data.template_file.resource-message.rendered
}

data "template_file" "resource-message" {
	   for_each = local.json_file
	   template = file(each.key)

    vars = {
		test = xyz
    }
}

locals {
  json_file = fileset("path.module","folder/*.tpl")
}

error response

Because data.template_file.resource-message has “for_each” set, its attributes must be accessed
│ on specific instances.

│ For example, to correlate with indices of a referring resource, use:
│ data.template_file.resource-message[each.key]

Well, yes, this would error…

You’ve used for_each so there are now multiple datasources, but you’re still trying to reference them here as if there was only one singular one:

However the template_file datasource is now deprecated. Migrate to the built-in templatefile() function instead.

Hi maxb I tried using for_each in the resource block. but it throws the same error.
I am pretty new to Terraform. How would I be able to do the same with templatefile()` function instead.

Thank you in advance.

resource "datadog_monitor_json" "monitor_json" {
    for_each = local.json_file

    monitor = templatefile(each.key, {test = xyz})
}

templatefile docs