다음을 통해 공유


적응형 카드 템플릿 작성 SDK

적응형 카드 템플릿 작성 SDK를 사용하면 지원되는 플랫폼에서 카드 템플릿을 실제 데이터로 쉽게 채울 수 있습니다.

이에 대해서는 적응형 카드 템플릿 작성 개요를 참조하세요.

중요

2020년 5월 릴리스 후보주요 변경 내용

템플릿을 출시하기 위해 열심히 일했고 마침내 마지막 단계에 접어들었습니다! 릴리스를 마무리할 때 약간의 주요 변경 사항을 적용해야 했습니다.

2020년 5월 현재 주요 변경 내용

  1. 바인딩 구문이 {...}에서 ${...}로 변경되었습니다.
    • 예를 들어, "text": "Hello {name}""text": "Hello ${name}"가 됩니다.
  2. JavaScript API는 더 이상 EvaluationContext 개체를 포함하지 않습니다. 데이터를 expand 함수에 전달하기만 하면 됩니다. 자세한 내용은 SDK 페이지를 참조하세요.
  3. .NET API는 JavaScript API와 더 가깝게 일치하도록 다시 디자인되었습니다. 전체 세부 정보는 아래를 참조하세요.

JavaScript

adaptivecards-templating 라이브러리는 npm 또는 CDN에서 사용할 수 있습니다. 전체 설명서는 패키지 링크를 참조하세요.

npm

npm install

npm install adaptivecards-templating

CDN

<script src="https://unpkg.com/adaptivecards-templating/dist/adaptivecards-templating.min.js"></script>

사용

아래 샘플에서는 카드를 렌더링하기 위해 adaptivecards 라이브러리도 설치했다고 가정합니다.

카드를 렌더링하지 않는 경우 parserender 코드를 제거할 수 있습니다.

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());

.NET

Nuget install

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);

사용자 지정 함수

미리 빌드된 함수 외에도 사용자 지정 함수를 Adaptive Expression Library에 추가할 수 있습니다.

아래 예제에서는 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);

문제 해결

Q. expand()를 호출하는 AdaptiveTemplateException이 발생하는 이유는 무엇인가요?
A. 오류 메시지가 행에서 '<문제가 있는 항목>'으로 표시되는 경우 '<줄 번호>'가 '$data : ' pair"에 대해 형식이 잘못된 것입니다.
"$Data"에 제공된 값이 숫자, 부울, 개체 및 배열 등의 유효한 json인지 확인하거나 적응형 템플릿 언어의 올바른 구문을 따르고 해당 줄 번호의 데이터 컨텍스트에 항목이 있는지 확인합니다.

Q. expand()를 호출하는 ArgumentNullException이 발생하는 이유는 무엇인가요?
A. 오류 메시지가 "상위 데이터 컨텍스트가 설정되었는지 확인하거나 '<문제가 있는 항목>', '<줄 번호>'"에 대해 null이 아닌 값을 입력하세요.
이는 요청된 데이터 바인딩에 대한 데이터 컨텍스트가 존재하지 않음을 나타냅니다. 루트 데이터 컨텍스트가 설정되어 있는지 확인하고, 이미 있는 경우, 줄 번호로 표시된 대로 현재 바인딩에 사용할 수 있는 데이터 컨텍스트가 있는지 확인합니다.

Q. "2017-02-14T06:08:00Z"처럼 RFC 3389 형식의 날짜/시간을 템플릿과 함께 사용하는 경우 TIME/DATE 함수에서 작동하지 않는 이유는 무엇입니까?
A. .NET sdk nuget 버전 1.0.0-rc.0에서 이러한 동작이 나타납니다. 이러한 동작은 이후 릴리스에서 수정되었습니다. json.Net deserilizer의 기본 동작은 날짜/시간 형식 문자열을 변경하고 후속 릴리스에서는 사용하지 않도록 설정됩니다. 이 예제에서처럼 formatDateTime() 함수를 사용하여 날짜/시간 문자열을 RFC 3389로 포맷하거나 TIME/DATE 함수를 생략하고 formatDateTime()을 사용하세요. formatDateTime()에 대한 자세한 내용은 여기로 이동하세요.