적응형 카드 템플릿 SDK를 사용하면 지원되는 모든 플랫폼에서 카드 템플릿 을 실제 데이터로 쉽게 채울 수 있습니다.
적응형 카드 템플릿의 개요는 이 문서를 참조하세요.
중요합니다
2020년 5월 릴리스 후보의주요 변경 내용
우리는 템플릿 기능을 출시하도록 열심히 일해 왔고, 마침내 마지막 단계에 와 있습니다! 릴리스를 앞두고 몇 가지 사소한 호환성을 손상시키는 변경을 해야 했습니다.
2020년 5월 현재 호환성이 손상되는 변경
- 바인딩 구문이
{...}에서${...}으로 변경되었습니다.- 예를 들어:
"text": "Hello {name}"가"text": "Hello ${name}"로 됩니다.
- 예를 들어:
- JavaScript API에 더 이상 개체가
EvaluationContext포함되지 않습니다. 데이터를expand함수에 그냥 전달하면 됩니다. 자세한 내용은 SDK 페이지를 참조하세요. - .NET API는 JavaScript API와 더 밀접하게 일치하도록 다시 디자인되었습니다. 자세한 내용은 아래를 참조하세요.
자바스크립트
적응 카드 템플릿 라이브러리는 npm 및 CDN을 통해 사용할 수 있습니다. 전체 설명서는 패키지 링크를 참조하세요.
npm
npm install adaptivecards-templating
CDN
<script src="https://unpkg.com/adaptivecards-templating/dist/adaptivecards-templating.min.js"></script>
사용법
아래 샘플에서는 카드를 렌더링하기 위해 적응형 카드 라이브러리도 설치했다고 가정합니다.
카드를 렌더링할 계획이 없는 경우 parse 및 render 코드를 제거할 수 있습니다.
import * as ACData from "adaptivecards-templating";
import * as AdaptiveCards from "adaptivecards";
// Define a template payload
var templatePayload = {
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "TextBlock",
"text": "Hello ${name}!"
}
]
};
// Create a Template instance from the template payload
var template = new ACData.Template(templatePayload);
// Expand the template with your `$root` data object.
// This binds it to the data and produces the final Adaptive Card payload
var cardPayload = template.expand({
$root: {
name: "Matt Hidinger"
}
});
// OPTIONAL: Render the card (requires that the adaptivecards library be loaded)
var adaptiveCard = new AdaptiveCards.AdaptiveCard();
adaptiveCard.parse(cardPayload);
document.getElementById('exampleDiv').appendChild(adaptiveCard.render());
닷넷
dotnet add package AdaptiveCards.Templating
사용법
// Import the library
using AdaptiveCards.Templating;
var templateJson = @"
{
""type"": ""AdaptiveCard"",
""version"": ""1.2"",
""body"": [
{
""type"": ""TextBlock"",
""text"": ""Hello ${name}!""
}
]
}";
// Create a Template instance from the template payload
AdaptiveCardTemplate template = new AdaptiveCardTemplate(templateJson);
// You can use any serializable object as your data
var myData = new
{
Name = "Matt Hidinger"
};
// "Expand" the template - this generates the final Adaptive Card payload
string cardJson = template.Expand(myData);
사용자 지정 함수
사용자 지정 함수는 미리 빌드된 함수 외에도 적응 식 라이브러리에 추가할 수 있습니다.
아래 예제에서는 stringFormat 사용자 지정 함수가 추가되었으며, 이 함수는 문자열 포맷에 사용됩니다.
string jsonTemplate = @"{
""type"": ""AdaptiveCard"",
""version"": ""1.0"",
""body"": [{
""type"": ""TextBlock"",
""text"": ""${stringFormat(strings.myName, person.firstName, person.lastName)}""
}]
}";
string jsonData = @"{
""strings"": {
""myName"": ""My name is {0} {1}""
},
""person"": {
""firstName"": ""Andrew"",
""lastName"": ""Leader""
}
}";
AdaptiveCardTemplate template = new AdaptiveCardTemplate(jsonTemplate);
var context = new EvaluationContext
{
Root = jsonData
};
// a custom function is added
AdaptiveExpressions.Expression.Functions.Add("stringFormat", (args) =>
{
string formattedString = "";
// argument is packed in sequential order as defined in the template
// For example, suppose we have "${stringFormat(strings.myName, person.firstName, person.lastName)}"
// args will have following entries
// args[0]: strings.myName
// args[1]: person.firstName
// args[2]: strings.lastName
if (args[0] != null && args[1] != null && args[2] != null)
{
string formatString = args[0];
string[] stringArguments = {args[1], args[2] };
formattedString = string.Format(formatString, stringArguments);
}
return formattedString;
});
string cardJson = template.Expand(context);
문제 해결
질문. AdaptiveTemplateException 호출 expand()이 실행되는 이유는 무엇인가요?
A. 오류 메시지가 줄에서 '<잘못된 항목>'처럼 보이면 '<$data: 'pair'에 대해 '줄 번호>'의 형식이 잘못되었습니다.
"$data"에 제공된 값이 숫자, 부울, 개체 및 배열과 같은 유효한 json이거나 적응 템플릿 언어에 대한 올바른 구문을 따르고 항목이 줄 번호의 데이터 컨텍스트에 있는지 확인하세요.
질문. ArgumentNullException 호출 expand()이 실행되는 이유는 무엇인가요?
A. 오류 메시지가 표시되는 경우" 부모 데이터 컨텍스트가 설정되어 있는지 확인하거나 줄에 '<잘못된 항목>'에 대해 null이 아닌 값을 입력하십시오. '<줄 번호>'".
요청된 데이터 바인딩에 대한 데이터 컨텍스트가 없음을 나타냅니다. 루트 데이터 컨텍스트가 설정된 경우 줄 번호로 표시된 대로 현재 바인딩에 사용할 수 있는 데이터 컨텍스트가 있는지 확인하세요.
질문. 템플릿과 함께 사용할 때 RFC 3389 형식의 날짜/시간(예: "2017-02-14T06:08:00Z")이 TIME/DATE 함수에서 작동하지 않는 이유는 무엇인가요?
A. .NET sdk nuget 버전 1.0.0-rc.0은 이 동작을 보여 줍니다. 이 동작은 후속 릴리스에서 수정됩니다. json.Net deserilizer의 기본 동작은 날짜/시간 형식 문자열을 변경하며 후속 릴리스에서는 사용하지 않도록 설정됩니다. formatDateTime() 함수를 사용하여 이 예제에 표시된 대로 날짜/시간 문자열의 서식을 RFC 3389로 지정하거나 TIME/DATE 함수를 바이패스하고 formatDateTime()만 사용할 수 있습니다. formatDateTime()에 대한 자세한 내용은 여기를 참조하세요.